简体   繁体   English

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

[英]How to declare a type as nullable in TypeScript?

I have an interface in TypeScript.我在TypeScript有一个接口。

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

I would like to make salary as a nullable field (Like we can do in C#).我想将salary设为可为空的字段(就像我们在 C# 中所做的那样)。 Is this possible to do in TypeScript?这可以在 TypeScript 中完成吗?

All fields in JavaScript (and in TypeScript) can have the value null or undefined . JavaScript(和 TypeScript)中的所有字段都可以具有值nullundefined

You can make the field optional which is different from nullable.您可以将字段设为可选,这与可为空不同。

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

Compare with:比较:

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

Union type is in my mind best option in this case:在这种情况下,联合类型是我认为的最佳选择:

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

EDIT : For this to work as expected, you should enable the strictNullChecks in tsconfig .编辑:为了按预期工作,您应该在strictNullChecks中启用tsconfig

To be more C# like, define the Nullable type like this:为了更像C#,像这样定义Nullable类型:

type Nullable<T> = T | null;

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

Bonus:奖金:

To make Nullable behave like a built in Typescript type, define it in a global.d.ts definition file in the root source folder.要使Nullable表现得像内置的 Typescript 类型,请在根源文件夹中的global.d.ts定义文件中定义它。 This path worked for me: /src/global.d.ts这条路径对我/src/global.d.ts/src/global.d.ts

Just add a question mark ?就加个问号? to the optional field.到可选字段。

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

You can just implement a user-defined type like the following:你可以只实现一个用户定义的类型,如下所示:

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];
type MyProps = {
  workoutType: string | null;
};

Nullable type can invoke runtime error.可空类型可以调用运行时错误。 So I think it's good to use a compiler option --strictNullChecks and declare number | null所以我认为最好使用编译器选项--strictNullChecks并声明number | null number | null as type. number | null作为类型。 also in case of nested function, although input type is null, compiler can not know what it could break, so I recommend use !同样在嵌套函数的情况下,虽然输入类型为空,但编译器不知道它会破坏什么,所以我建议使用! (exclamination mark). (感叹号)。

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

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

I solved this issue by editing the tsconfig.json file.我通过编辑 tsconfig.json 文件解决了这个问题。

Under: "strict": true , add those 2 lines:在: "strict": true下,添加这两行:

"noImplicitAny": false,
"strictNullChecks": false,
type Nullable<T> = {
  [P in keyof T]: T[P] | null;
};

and then u can use it然后你可以使用它

Nullable<Employee>

This way you can still use Employee interface as it is somewhere else这样您仍然可以使用Employee接口,因为它在其他地方

i had this same question a while back.. all types in ts are nullable, because void is a subtype of all types (unlike, for example, scala).不久前我遇到了同样的问题.. ts 中的所有类型都可以为空,因为 void 是所有类型的子类型(与例如 scala 不同)。

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

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
}

Or you can turn off strictNullChecks;)或者您可以关闭 strictNullChecks;)

And the reversed version:而相反的版本:

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

把你的号码的价值定义为未定义

var user: Employee = { name: null, salary: undefined }; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM