Reputation: 321
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;
}
Upvotes: 5
Views: 7533
Reputation: 191799
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;
Upvotes: 11