繁体   English   中英

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

[英]How can i make multiple type property interface on 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM