如何在 TypeScript 中将类型声明为可为空的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17220114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare a type as nullable in TypeScript?
提问by Amitabh
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#). Is this possible to do in TypeScript?
我想将 'salary' 作为一个可以为空的字段(就像我们在 C# 中可以做的那样)。这可以在 TypeScript 中做到吗?
回答by Ryan Cavanaugh
All fields in JavaScript (and in TypeScript) can have the value null
or undefined
.
JavaScript(和 TypeScript)中的所有字段都可以具有值null
或undefined
。
You can make the field optionalwhich 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';
}
回答by bjaksic
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
in tsconfig
.
回答by Tim Santeford
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. This path worked for me: /src/global.d.ts
要使Nullable
行为类似于内置的 Typescript 类型,请global.d.ts
在根源文件夹中的定义文件中定义它。这条路对我有用:/src/global.d.ts
回答by Miguel Ventura
Just add a question mark ?
to the optional field.
只需?
在可选字段中添加一个问号即可。
interface Employee{
id: number;
name: string;
salary?: number;
}
回答by Willem van der Veen
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];
回答by Ritwik
type MyProps = {
workoutType: string | null;
};
回答by bcherny
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
回答by Margaux
Nullable type can invoke runtime error.
So I think it's good to use a compiler option --strictNullChecks
and declare number | null
as type. 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).
可空类型可以调用运行时错误。所以我认为最好使用编译器选项--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");
}
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
回答by Abdus Salam Azad
put value of your number as undefined
将您的数字值设为未定义
var user: Employee = { name: null, salary: undefined };