我有一个接口在TypeScript。
interface Employee{
id: number;
name: string;
salary: number;
}
我想把工资作为一个可空字段(就像我们可以在c#中做的那样)。这可能在TypeScript中实现吗?
我有一个接口在TypeScript。
interface Employee{
id: number;
name: string;
salary: number;
}
我想把工资作为一个可空字段(就像我们可以在c#中做的那样)。这可能在TypeScript中实现吗?
当前回答
我通过编辑tsconfig解决了这个问题。json文件。
下面:"strict": true, 加上这两行:
"noImplicitAny": false,
"strictNullChecks": false,
其他回答
就加个问号?到可选字段。
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 Nullable<T> = {
[P in keyof T]: T[P] | null;
};
然后你就可以用它了
Nullable<Employee>
这样,您仍然可以像在其他地方一样使用Employee界面
type MyProps = {
workoutType: string | null;
};
我通过编辑tsconfig解决了这个问题。json文件。
下面:"strict": true, 加上这两行:
"noImplicitAny": false,
"strictNullChecks": false,