打字稿:接口联合 <Interface1 |接口2>

时间:2021-07-13 21:21:05

标签: typescript

我有以下模拟 API 返回的数据结构的接口:

interface IVehicle {
  color: string;
  wheels: number;
  brand: string;
}

interface IHouse {
  color: string;
  bedrooms: number;
  bathrooms: number;
}

API 响应返回一个列表,例如 [{Car1}, {Car2}, {Car3}, {House1}],因此在为该数据结构声明类型时,合乎逻辑的做法是使用 <IVehicle | IHouse>;但是,当我尝试访问一个对象中的值而另一个对象中不存在该键时,Typescript 会引发错误。

class MyClass extends Record({
  apiResponse: Array<IVehicle | IHouse>(),
}) {

  apiResponse.map((house) => house.bedrooms) 
  //                               ^^^^^^^^
  // Property 'bedrooms' does not exist on type 'IVehicle | IHouse'.

}

我无法更改 API 响应。如何在 Typescript 中声明这样的类型?

0 个答案:

没有答案