It is worth mentioning that your code is functional, as properties can be defined to accept a range of types by utilizing the |
operator, known as a Union Type.
When dealing with union types, it may be necessary to implement type guards or casts in situations where you need to access properties that are specific to only certain types within the list. For instance:
const demo: Demo = {
payload: {
id: '1',
name: 'boo',
},
};
const demo2: Demo = {
payload: {
id: '1',
price: 25,
},
};
// Property is common to all types
demo.payload.id;
// Without explicit casting, accessing these properties will result in errors
(demo.payload as IPayload1).name;
(demo.payload as IPayload2).price;