seg*_*egu 3 interface typescript typescript-typings
我想在打字稿中使用两个不同的接口创建接口属性。这可能吗?
interface IPayload1 {
id: string;
name: string;
}
interface IPayload2 {
id: string;
price: number;
}
interface Demo {
// Can this be possible?
payload: IPayload1 | IPayload2;
}
Run Code Online (Sandbox Code Playgroud)
您的代码将起作用,并且可以说属性可以是使用|. 这称为联合类型。
请注意,在使用联合类型时,您可能需要使用类型保护或强制转换,以防您想要访问特定于少于所有列出类型的属性。例如:
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4056 次 |
| 最近记录: |