ChatGPT解决这个技术问题 Extra ChatGPT

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

我在 TypeScript 中有一个界面。

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

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


R
Ryan Cavanaugh

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

与之比较:

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

看起来 strictly nullable types and strict null-checks 已经实现,并将与 Typescript 2.0 一起出现! (或现在的 typescript@next。)
您确定第一个示例中的 var c 吗?在我看来, var b 和 var c 在那里是一样的。
这是不正确的。 JS 区分 null 和 undefined。正确的代码应该是 salary:number|null; 如果你这样做 salary?:number; salary = null; 你会得到一个错误。但是,salary = undefined; 在这种情况下可以正常工作。解决方法:使用 Union 即 '|'
(投反对票,因为它现在已经过时/不是好的做法。)
嗯,为什么不| null。你自己说 undefined 和 null 不一样。 Optional 是未定义的,所以这根本不是答案吗?
T
Tim Santeford

要更像 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


使用它会破坏对象属性的自动完成。例如,如果我们有 emp: Partial<Employee>,我们可以做 emp.idemp.name 等,但如果我们有 emp: Nullable<Employee>,我们不能做 emp.id
这是问题的实际答案。
@YousufKhan 这是真的。这可能是因为因为 emp 可能为空,所以 id 属性可能无效。为了使代码健壮,您可能应该首先使用 if 块来检查 null,如下所示:if (emp) { console.log(emp.id); } 如果您使用这样的 if 块,TypeScript 编译器和编辑器“看到”该对象块内不为空,因此不会产生错误并允许在 if 块内自动完成。 (它在我的 Visual Studio 2019 编辑器中运行良好,我认为它也可以在 Visual Studio Code 中运行。但我不了解其他编辑器。)
@优素福汗。 . .使用 emp: Partial<Employee> 时,生成的类型包含 Employee 中的所有属性,但这些属性可以为空。 (嗯,undefinedable 在这里可能是更合适的术语。)所以 emp 的所有属性都可用,但可以为空。使用 emp: Nullable<Employee> 时,emp 变量本身可以为空。如果它不为 null,它应该是一个有效的完整 Employee 实例。您也可以将它们组合起来:emp: Nullable<Partial<Employee>>。在这种情况下,emp 本身可以为空,但当不为空时,它的属性也都可以为空。
你能像 C# 中的 Nullable 一样添加 Value 和 HasValue 吗?可能会使用泛型类,但您也必须实例化它,而不仅仅是使用类型声明。
i
i.am.michiel

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

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

编辑:要按预期工作,您应该在 tsconfig 中启用 strictNullChecks


如果您使用 --strictNullChecks (您应该这样做),这是一个有效的解决方案。我不会使用它来支持可选成员,因为它会强制您在所有文字对象上添加显式 null,但对于函数返回值,这是要走的路。
澄清@geon 的建议:接口的optional property? 属性名称 声明。 salary?: number 表示可以省略 salary,或者等价地给定值 undefined,但不能给它值 nullGood demonstration of different declarations using optional and/or null
@ToolmakerSteve 是的。使用 salary: number | nullsalary: number | undefined 仍然很好,因为它会强制您将其设置为某个值,即使该值是 undefined。否则很容易忘记。
M
Miguel Ventura

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

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

正如瑞安指出的那样......?表示打字稿中的可选,不可为空。没有 ?表示 var 必须设置为包括 null 或 undefined 的值。和 ?你可以跳过整个声明。
谢谢!我搜索了“typescript optional value”,所以这正是我想要的。
根据@HeNrik 的评论:这是对与所问问题略有不同的问题的答案。自 2016 年的 2.0 起,Here is a good demonstration of all possible combinations of optional / undefined / null when declaring a type
W
Willem van der Veen

您可以只实现一个用户定义的类型,如下所示:

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

R
Ritwik
type MyProps = {
  workoutType: string | null;
};

M
Margaux

可空类型可以调用运行时错误。所以我认为最好使用编译器选项 --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");
}

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


两条评论:a) 现代 JS 或 TS 可以使用“null-coalesce”运算符 ??。与“错误”逻辑或运算符 || 相比,这不太可能导致意外错误。 name = name ?? "Bob"; 是用默认值替换 null 的更简洁的方法。 b) 我不会在这段代码中使用 !。任何时候使用 !,都可能让未来的代码维护者犯错,从而导致罕见的运行时错误:调试起来很痛苦。 const name2:string = name ?? "Bob"; function postfix(...) { return name2.charAt(0) ... 更安全
T
Tobias S.

我通过编辑 tsconfig.json 文件解决了这个问题。

在:"strict": true 下,添加这两行:

"noImplicitAny": false,
"strictNullChecks": false,

这不会违背打字稿的目的吗?肯定有办法将对象属性或对象设置为某种空安全状态吗?
@d0rf47,我尚未对其进行测试,但我认为您可以将 NonNullable 助手用于该用例 typescriptlang.org/docs/handbook/…
b
bcherny

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

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


-1:这根本不是真的。至于 void 是“所有类型的子类型”(bottom type),请参阅 this thread。此外,您为 scala 提供的图表也不正确。 scala 中的 Nothing 实际上是底部类型。 Typescript, atm, 没有 有底部类型,而 scala
“所有类型的子类型”!= 底部类型。在此处查看 TS 规范 github.com/Microsoft/TypeScript/blob/master/doc/…
Y
Yilmaz
type Nullable<T> = {
  [P in keyof T]: T[P] | null;
};

然后你可以使用它

Nullable<Employee>

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


S
Shura
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
}

或者您可以关闭 strictNullChecks ;)

和相反的版本:

type WithNonNullableFields<T, Fields> = {
  [K in keyof T]: K extends Fields
    ? NonNullable<T[K]>
    : T[K]
}