接口中的 Typescript 继承

Typescript Inheritance in Interfaces

第一次使用打字稿,想知道如何最好地处理这种情况。

我有一些 json 数据来自 API,比方说

{"name" : "A Person", "age": "25", createdAt: "timestamp"}

我有一个 IPersonData 接口,代表传入的 JSON。

export interface IPersonData {
  name: string;
  createdAt: string;
  age: string;
}

但是系统中有一个实际的 Person 对象:

export interface IPerson extends IPersonData {
  createdAt: DateTime; //this is the luxon DateTime
  age: number;
}

Webstorm 没有对我大吼大叫(实际上提供了一个图标说它被覆盖了)但是编译器讨厌它,让我知道 Type 'DateTime' is not assignable to type 'string'.

我也试过了,

 export interface IPerson extends Omit<IPersonData, "createdAt">{
  createdAt: DateTime; //this is the luxon DateTime
  age: number;
}

我可以在 typescript 中覆盖吗?如果不能,表示 JSON 进入系统是否有价值,(我们使用相同的类型来验证 JSON 离开 API).

你几乎完成了你的最后一个片段。您可能遇到了这个错误:

Interface 'IPerson' incorrectly extends interface 'Omit<IPersonData, "createdAt">'.
  Types of property 'age' are incompatible.
    Type 'number' is not assignable to type 'string'.(2430)

需要注意的重要一点是不是抱怨createdAt。所以它在那个领域工作。由于您要将 agestring 更改为 number,因此您也需要省略那个。

您可能不知道的一件事是,您可以通过传入字符串并集来使用 Omit 省略许多字段。

export interface IPerson extends Omit<IPersonData, 'createdAt' | 'age'> {
  createdAt: DateTime;
  age: number;
}

符合您的预期。

Playground