如何在TypeScript中声明一个types为空?
我在TypeScript中有一个接口。
interface Employee{ id: number; name: string; salary: number; }
我想把“工资”作为一个可空字段(就像我们在C#中可以做的那样)。 这可能在TypeScript中做到吗?
JavaScript(和TypeScript)中的所有字段可以具有值null
或undefined
。
你可以使这个字段是可选的 ,而不是空的。
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'; }
只需添加一个问号?
到可选字段。
interface Employee{ id: number; name: string; salary?: number; }
在这种情况下,联盟types是我心目中最好的select:
interface Employee{ id: number; name: string; salary: number | null; } // Both cases are valid let employe1: Employee = { id: 1, name: 'John', salary: 100 }; let employe2: Employee = { id: 1, name: 'John', salary: null };
我有一个相同的问题回来.. ts中的所有types都是可空的,因为void是所有types的子types(不像,例如,斯卡拉)。
看看这个stream程图是否有帮助 – https://github.com/bcherny/language-types-comparison#typescript