TypeScript で型を null 許容型として宣言するにはどうすればよいでしょうか? 質問する

TypeScript で型を null 許容型として宣言するにはどうすればよいでしょうか? 質問する

TypeScript にインターフェースがあります。

interface Employee{
    id: number;
    name: string;
    salary: number;
}

salarynull 許容フィールドを作成したいと思います(C# で実行できるように)。これは TypeScript で実行できますか?

ベストアンサー1

JavaScript (および TypeScript) のすべてのフィールドには、nullまたは という値を設定できますundefined

フィールドを、null 可能とは異なるオプションにすることができます。

interface Employee1 {
    name: string;
    salary: number;
}

var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK

// OK
class SomeEmployeeA implements Employee1 {
    public name = 'Bob';
    public salary = 40000;
}

// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
    public name: string;
}

と比べて:

interface Employee2 {
    name: string;
    salary?: number;
}

var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number

// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
    public name = 'Bob';
}

おすすめ記事