我有一个接口在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 MyProps = {
  workoutType: string | null;
};

在我看来,联合类型在这种情况下是最好的选择:

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。

type Nullable<T> = {
  [P in keyof T]: T[P] | null;
};

然后你就可以用它了

Nullable<Employee>

这样,您仍然可以像在其他地方一样使用Employee界面

为了更像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

就加个问号?到可选字段。

interface Employee{
   id: number;
   name: string;
   salary?: number;
}