如何在TypeScript中将类型声明为可为空?


247

我在TypeScript中有一个接口。

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

我想将其salary设为可为空的字段(就像我们可以在C#中那样)。这可以在TypeScript中完成吗?

Answers:


274

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

35
看起来严格可空的类型和严格的空检查已实现,并将随Typescript 2.0一起提供!(或typescript@next现在。)
mindplay.dk

您确定第一个示例中的var c吗?在我看来,var b和var c相同。
martinp999 '19

为了设置没有编译错误的null或undefined值,必须删除tsconfig的“ strict”选项或将其等于“ false”"strict" : false
Nicolas Janel

1
这是不正确的。JS区分null和undefined。正确的代码应该是salary:number|null;如果您这样做,salary?:number; salary = null;则会出现错误。但是,salary = undefined;在这种情况下可以正常工作。解决方案:使用联合,即“ |”
Ankur Nigam

125

在这种情况下,我认为联合类型是最佳选择:

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

编辑:为使此功能按预期工作,应启用strictNullChecksin tsconfig


9
如果使用--strictNullChecks(应使用),则这是有效的解决方案。我不会使用它来支持可选成员,因为它会强制您在所有文字对象上添加一个显式的null,但是对于函数返回值而言,这是必须的方法。
乔治,

77

要更像C#,请定义以下Nullable类型:

type Nullable<T> = T | null;

interface Employee{
   id: number;
   name: string;
   salary: Nullable<number>;
}

奖金:

要使Nullable行为类似于内置的Typescript类型,请global.d.ts在根源文件夹的定义文件中对其进行定义。这条路对我有用:/src/global.d.ts


1
我最喜欢的答案- 直接回答问题,无需阅读。
Lqueryvg

1
使用此方法会破坏对象属性的自动完成。例如,如果我们拥有emp: Partial<Employee>,我们可以做某事emp.idemp.name等等,但是如果我们拥有emp: Nullable<Employee>,我们就不能做emp.id
Yousuf Khan

1
这是对该问题的实际答案。
Patrick

36

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

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

54
正如Ryan所指出的...?表示打字稿中的可选内容,不能为空。没有?表示var必须设置为包含null或undefined的值。用?您可以跳过整个声明内容。
他恩里克(Nrik)2015年

3
谢谢!我用谷歌搜索“打字稿可选值”,所以这正是我在寻找的东西。
陌生人研究员

13

您可以像下面这样实现用户定义的类型:

type Nullable<T> = T | undefined | null;

var foo: Nullable<number> = 10; // ok
var bar: Nullable<number> = true; // type 'true' is not assignable to type 'Nullable<number>'
var baz: Nullable<number> = null; // ok

var arr1: Nullable<Array<number>> = [1,2]; // ok
var obj: Nullable<Object> = {}; // ok

 // Type 'number[]' is not assignable to type 'string[]'. 
 // Type 'number' is not assignable to type 'string'
var arr2: Nullable<Array<string>> = [1,2];


4

不久前我也遇到了同样的问题。ts中的所有类型都是可为空的,因为void是所有类型的子类型(例如,与scala不同)。

查看此流程图是否有帮助-https: //github.com/bcherny/language-types-comparison#typescript


2
-1:完全不正确。至于void“所有类型的子类型”(底部类型),请参考此线程。同样,您为scala提供的图表也不正确。Nothing实际上,在scala中,bottom是底部类型。打字稿atm 没有底部字体,而scala 却没有
Daniel Shin

2
“所有类型的子类型”!=底部类型。在此处查看TS规范github.com/Microsoft/TypeScript/blob/master/doc/…–
bcherny

3

可空类型可以调用运行时错误。因此,我认为最好使用编译器选项--strictNullChecks并声明number | null为类型。同样在嵌套函数的情况下,尽管输入类型为null,但编译器不知道它可能会中断,因此我建议使用!(感叹号)。

function broken(name: string | null): string {
  function postfix(epithet: string) {
    return name.charAt(0) + '.  the ' + epithet; // error, 'name' is possibly null
  }
  name = name || "Bob";
  return postfix("great");
}

function fixed(name: string | null): string {
  function postfix(epithet: string) {
    return name!.charAt(0) + '.  the ' + epithet; // ok
  }
  name = name || "Bob";
  return postfix("great");
}

参考。 https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.