简体   繁体   English

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

[英]How can i make multiple type property interface on typescript

I want to make interface property with two diferent interfaces in typescript. 我想在打字稿中使用两个不同的接口制作接口属性。 can this be possible? 这可能吗?

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

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

Your code will work, and it is possible to say that a property can be one of a list of types using | 您的代码将起作用,并且可以使用|表示属性可以是类型列表之一| . This is called a Union Type . 这称为联合类型

Note that when working with union types, you may need to use type guards or cast in cases where you want to access properties that are specific to fewer than all of the listed types. 请注意,使用联合类型时,如果要访问特定于少于所有列出类型的属性,则可能需要使用类型保护或强制类型转换。 For example: 例如:

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