如何在typescript上创建多类型属性接口

如何在typescript上创建多类型属性接口,typescript,interface,typescript-typings,Typescript,Interface,Typescript Typings,我想用typescript中的两个不同接口创建接口属性。这可能吗 interface IPayload1 { id: string; name: string; } interface IPayload2 { id: string; price: number; } interface Demo { // Can this be possible? payload: IPayload1 | IPayload2; } 您的代码将正常工作,可以使用说属性可以是类型列表中的

我想用typescript中的两个不同接口创建接口属性。这可能吗

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

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

您的代码将正常工作,可以使用
说属性可以是类型列表中的一种。这被称为一个

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

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;

payload?:IPAILOAD1 | IPAILOAD2
将使其成为可选的对不起,对于可选字,我不需要可选参数,需要有效负载。您的代码看起来很好。什么坏了?谢谢。这就是我一直在寻找的答案。很好的答案。谢谢:)