我有一个接口在TypeScript。
interface Employee{
id: number;
name: string;
salary: number;
}
我想把工资作为一个可空字段(就像我们可以在c#中做的那样)。这可能在TypeScript中实现吗?
我有一个接口在TypeScript。
interface Employee{
id: number;
name: string;
salary: number;
}
我想把工资作为一个可空字段(就像我们可以在c#中做的那样)。这可能在TypeScript中实现吗?
当前回答
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]
}
type MyProps = {
workoutType: string | null;
};
type Nullable<T> = {
[P in keyof T]: T[P] | null;
};
然后你就可以用它了
Nullable<Employee>
这样,您仍然可以像在其他地方一样使用Employee界面
可空类型可以调用运行时错误。 所以我认为使用编译器选项strictNullChecks并将数字| null声明为类型是很好的。同样在嵌套函数的情况下,虽然输入类型是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
我通过编辑tsconfig解决了这个问题。json文件。
下面:"strict": true, 加上这两行:
"noImplicitAny": false,
"strictNullChecks": false,