I have defined a union of two types in my code. Here are the definitions:
type Generic = {
subtype: undefined,
user: string,
text: string
}
type Other = {
subtype:'message',
text: string
}
type Message = Generic | Other;
Within my code, I am using the following condition:
function getMessage(event: Message) {
if (event.subtype === undefined) console.log(event.user); // This should work because only Generic has subtype === undefined and it has a user property
}
However, when running this code, TypeScript raises an error stating
Property user does not exist on type Message
. Shouldn't it work since it is within the if
condition that checks for subtype
? How can I resolve this issue, especially if these type definitions come from a library over which I have no control?