我有一个接口在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 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]
}

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

我通过编辑tsconfig解决了这个问题。json文件。

下面:"strict": true, 加上这两行:

"noImplicitAny": false,
"strictNullChecks": false,
type MyProps = {
  workoutType: string | null;
};