我想在打字稿中使用两个不同的接口制作接口属性。可以吗?
interface IPayload1 {
id: string;
name: string;
}
interface IPayload2 {
id: string;
price: number;
}
interface Demo {
// Can this be possible?
payload: IPayload1 | IPayload2;
}
答案 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;