I'm working with a simple feature related to display some messages, the basic message structure is the same, but there's a data field matching each type of messages with different structure. The rough example is like the following.
type MessageBase = {
id: number;
data: B | C;
};
type B = {
title: string;
body: string;
};
type C = {
url: string;
};
const message: MessageBase = {
id: 1,
data: {
body: "Hello",
title: "World",
},
};
// all above code work fine
I thought it'll be like some simple union, data could be either type B or type C, great!
type Demo = string | number
const demo: Demo = 'Hello' // demo could be either string or number
But when I try to use the type in actual components, ts throws a warning saying
const { title } = message.data;
Property 'title' does not exist on type 'B | C'
Could anyone help pointing out where did I go wrong? Any suggestions would help, thank you guys in advanced!