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

Ami*_*abh 202 javascript typescript

我在TypeScript中有一个接口.

interface Employee{
   id: number;
   name: string;
   salary: number;
}
Run Code Online (Sandbox Code Playgroud)

我想把'薪水'作为一个可以为空的领域(就像我们在C#中所做的那样).这可以在TypeScript中做到吗?

Rya*_*ugh 238

JavaScript(和TypeScript)中的所有字段都可以具有值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;
}
Run Code Online (Sandbox Code Playgroud)

与之比较:

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';
}
Run Code Online (Sandbox Code Playgroud)

  • 看起来像[严格可空的类型和严格的空检查](https://github.com/Microsoft/TypeScript/pull/7140)已经实现,并将与Typescript 2.0一起到货!(或`typescript @ next` now.) (30认同)
  • 这是不正确的。JS 区分 null 和 undefined。正确的代码应该是 `salary:number|null;` 如果你这样做 `salary?:number; salary = null;` 你会得到一个错误。然而,在这种情况下,`salary = undefined;` 就可以正常工作。解决办法:使用Union即'|' (11认同)
  • (投反对票,因为它现在已经过时/不是好的做法。) (3认同)

bja*_*sic 104

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

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 };
Run Code Online (Sandbox Code Playgroud)

编辑:为了使其按预期工作,您应该启用strictNullChecksin tsconfig.

  • 如果你使用--strictNullChecks(你应该),这是一个有效的解决方案.我不会使用它来支持可选成员,因为它强制你在所有文字对象上添加一个显式null,但对于函数返回值,它是要走的路. (8认同)

Tim*_*ord 45

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

type Nullable<T> = T | null;

interface Employee{
   id: number;
   name: string;
   salary: Nullable<number>;
}
Run Code Online (Sandbox Code Playgroud)

  • @YousufKhan 确实如此。这可能是因为由于“emp”可能可为空,因此“id”属性可能无效。为了使代码健壮,您可能应该首先使用 `if` 块来检查 null,如下所示: `if (emp) { console.log(emp.id); 如果您使用这样的“if”块,TypeScript 编译器和编辑器会“看到”块内的对象不为空,因此不会生成错误并允许在 if 块内自动完成。(它在我的 Visual Studio 2019 编辑器中运行良好,我认为它也可以在 Visual Studio Code 中运行。但我不知道其他编辑器。) (5认同)
  • 我最喜欢的答案 - *直接*回答问题而不阅读它。 (4认同)
  • 使用此功能会破坏对象属性的自动完成。例如,如果我们有“emp: Partial&lt;Employee&gt;”,我们可以执行“emp.id”或“emp.name”等,但如果我们有“emp: Nullable&lt;Employee&gt;”,我们就不能执行“emp.id”或“emp.name”等。 id` (2认同)

Mig*_*ura 30

只需?在可选字段中添加问号即可.

interface Employee{
   id: number;
   name: string;
   salary?: number;
}
Run Code Online (Sandbox Code Playgroud)

  • 瑞恩指出......?在typescript中可选,不可为空.没有?表示var必须设置为包含null或undefined的值.用?你可以跳过整个声明 - 东西. (45认同)
  • 谢谢你!我在谷歌上搜索“打字稿可选值”,所以这正是我正在寻找的。 (4认同)
  • 根据@HeNrik 的评论:这是对与所问问题略有不同的问题的回答。自2016年的2.0以来,[这里很好地演示了声明类型时可选/未定义/null的所有可能组合](/sf/answers/4007065191/)。 (3认同)

Yil*_*maz 19

type Nullable<T> = {
  [P in keyof T]: T[P] | null;
};
Run Code Online (Sandbox Code Playgroud)

然后你就可以使用它了

Nullable<Employee>
Run Code Online (Sandbox Code Playgroud)

这样你仍然可以使用Employee接口,因为它在其他地方


Rit*_*wik 10

type MyProps = {
  workoutType: string | null;
};
Run Code Online (Sandbox Code Playgroud)


小智 8

可空类型可能会引发运行时错误。所以我认为最好使用编译器选项--strictNullChecks并声明number | 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");
}
Run Code Online (Sandbox Code Playgroud)

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


Shu*_*ura 8

type WithNullableFields<T, Fields> = {
  [K in keyof T]: K extends Fields 
    ? T[K] | null | undefined
    : T[K]
}

let employeeWithNullableSalary: WithNullableFields<Employee, "salary"> = {
  id: 1,
  name: "John",
  salary: null
}
Run Code Online (Sandbox Code Playgroud)

或者您可以关闭 strictNullChecks ;)

以及相反的版本:

type WithNonNullableFields<T, Fields> = {
  [K in keyof T]: K extends Fields
    ? NonNullable<T[K]>
    : T[K]
}
Run Code Online (Sandbox Code Playgroud)


Wil*_*een 6

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

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];
Run Code Online (Sandbox Code Playgroud)

  • 这太棒了,恕我直言,应该将其作为默认的 TypeScript 的一部分! (3认同)