我在 TypeScript 中有一个界面。
interface Employee{
id: number;
name: string;
salary: number;
}
我想将 salary
设为可空字段(就像我们在 C# 中可以做的那样)。这可以在 TypeScript 中完成吗?
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';
}
要更像 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.id
或 emp.name
等,但如果我们有 emp: Nullable<Employee>
,我们不能做 emp.id
emp
可能为空,所以 id
属性可能无效。为了使代码健壮,您可能应该首先使用 if
块来检查 null,如下所示:if (emp) { console.log(emp.id); }
如果您使用这样的 if
块,TypeScript 编译器和编辑器“看到”该对象块内不为空,因此不会产生错误并允许在 if 块内自动完成。 (它在我的 Visual Studio 2019 编辑器中运行良好,我认为它也可以在 Visual Studio Code 中运行。但我不了解其他编辑器。)
emp: Partial<Employee>
时,生成的类型包含 Employee
中的所有属性,但这些属性可以为空。 (嗯,undefined
able 在这里可能是更合适的术语。)所以 emp
的所有属性都可用,但可以为空。使用 emp: Nullable<Employee>
时,emp
变量本身可以为空。如果它不为 null,它应该是一个有效的完整 Employee
实例。您也可以将它们组合起来:emp: Nullable<Partial<Employee>>
。在这种情况下,emp
本身可以为空,但当不为空时,它的属性也都可以为空。
在这种情况下,联合类型是我认为的最佳选择:
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
。
optional property
用?
属性名称 声明。 salary?: number
表示可以省略 salary
,或者等价地给定值 undefined
,但不能给它值 null
。 Good demonstration of different declarations using optional and/or null。
salary: number | null
或 salary: number | undefined
仍然很好,因为它会强制您将其设置为某个值,即使该值是 undefined
。否则很容易忘记。
只需在可选字段中添加一个问号 ?
。
interface Employee{
id: number;
name: string;
salary?: number;
}
您可以只实现一个用户定义的类型,如下所示:
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;
};
可空类型可以调用运行时错误。所以我认为最好使用编译器选项 --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
??
。与“错误”逻辑或运算符 ||
相比,这不太可能导致意外错误。 name = name ?? "Bob";
是用默认值替换 null
的更简洁的方法。 b) 我不会在这段代码中使用 !
。任何时候使用 !
,都可能让未来的代码维护者犯错,从而导致罕见的运行时错误:调试起来很痛苦。 const name2:string = name ?? "Bob";
function postfix(...) { return name2.charAt(0) ...
更安全
我通过编辑 tsconfig.json 文件解决了这个问题。
在:"strict": true
下,添加这两行:
"noImplicitAny": false,
"strictNullChecks": false,
不久前我也有同样的问题.. ts 中的所有类型都是可以为空的,因为 void 是所有类型的子类型(例如,与 scala 不同)。
看看这个流程图是否有帮助 - https://github.com/bcherny/language-types-comparison#typescript
void
是“所有类型的子类型”(bottom type),请参阅 this thread。此外,您为 scala 提供的图表也不正确。 scala 中的 Nothing
实际上是底部类型。 Typescript, atm, 没有 有底部类型,而 scala 有。
type Nullable<T> = {
[P in keyof T]: T[P] | null;
};
然后你可以使用它
Nullable<Employee>
这样您仍然可以使用 Employee
接口,因为它在其他地方
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]
}
typescript@next
。)salary:number|null;
如果你这样做salary?:number; salary = null;
你会得到一个错误。但是,salary = undefined;
在这种情况下可以正常工作。解决方法:使用 Union 即 '|'| null
。你自己说 undefined 和 null 不一样。 Optional 是未定义的,所以这根本不是答案吗?