1

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!

DannyWang
  • 103
  • 1
  • 4
  • TypeScript doesn't let you index into a value if it's not sure that the index is present. Since there might or might not be a `title` property in a value of type `B | C` this isn't safe. See the answers to the linked questions for ways to proceed. – jcalz May 17 '22 at 19:01
  • noted, makes sense. I'll check out the linked question. Thank you! – DannyWang May 17 '22 at 19:03

0 Answers0