我如何在打字稿上制作多类型属性界面

时间:2018-10-30 12:48:08

标签: typescript interface typescript-typings

我想在打字稿中使用两个不同的接口制作接口属性。可以吗?

interface IPayload1 {
  id: string;
  name: string;
}
interface IPayload2 {
  id: string;
  price: number;
}

interface Demo {
  // Can this be possible?
  payload: IPayload1 | IPayload2;
}

1 个答案:

答案 0 :(得分:2)

您的代码将起作用,并且可以说|可以使属性成为类型列表之一。这称为Union Type

请注意,在使用联合类型时,如果要访问特定于少于所有列出类型的属性,则可能需要使用类型保护或强制类型转换。例如:

const demo: Demo = {
  payload: {
    id: '1',
    name: 'boo',
  },
};

const demo2: Demo = {
  payload: {
    id: '1',
    price: 25,
  },
};

// property is shared between types
demo.payload.id;

// If you do not cast, these will yield errors because the properties are not shared
(demo.payload as IPayload1).name;
(demo.payload as IPayload2).price;