2013-06-20 53 views
83

我在TypeScript中有一个接口。如何在TypeScript中声明一个可为空的类型?

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

我想提出“工资”作为一个可空场(就像我们可以用C#做​​的)。这可能在TypeScript中做到吗?

+0

'工资?:数;' –

+2

不,这不是真的。 –

+3

“工资?:数量”是错误的,这意味着薪水是可选的,而不是在C#可空的 – squadwuschel

回答

133

在JavaScript(和在打字稿)所有字段可以具有值nullundefined

您可以使字段可选这是不同于可空。

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'; 
} 
+9

看起来像[严格可为空的类型和严格的空检查](https://github.com/Microsoft/TypeScript/pull/7140)已经实现并将与Typescript 2.0一起到达! (或'typecript @ next') –

25

只需在可选字段中添加一个问号?即可。

interface Employee{ 
    id: number; 
    name: string; 
    salary?: number; 
} 
+21

正如Ryan指出的那样...?意味着打字稿中可选,不可空。 没有?意味着var必须设置为包含null或undefined的值。 With?你可以跳过整个声明。 –

5

我有同样的问题而回。在TS所有的类型都是空的,因为空虚是所有类型的亚型(不像,例如,斯卡拉) 。

看看该流程图帮助 - https://github.com/bcherny/language-types-comparison#typescript

+1

-1:这根本不是真的。至于'void'是'所有类型的子类型'([bottom type](https://en.wikipedia.org/wiki/Bottom_type)),请参考[this thread](https://github.com/Microsoft /打字稿/问题/ 3076)。您为scala提供的图表也不正确。实际上,Scala中没有什么是最基本的类型。 Typescript,atm,**不具有底部类型,而scala **具有**。 –

+0

“所有类型的子类型”!=底部类型。见这里的TS规范https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#327-the-undefined-type – bcherny

29

联盟类型是在这种情况下,我心中最好的选择:

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 }; 
+1

如果你使用--strictNullChecks(你应该),这是一个有效的方案。我不会使用它来支持可选成员,因为它会强制你在所有的文字对象上添加一个显式的空值,但是对于函数返回值来说,这是一条路。 – geon

相关问题