Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to narrow union types in array with typescript?

I’m trying to put together some data, that’s an array of union types, and process it accrodingly. I don’t understand why typescript can’t narrow this union types down:

interface BaseEvent {
    id: number;
}

interface EventA extends BaseEvent {
    attrA: string;
}

interface EventB extends BaseEvent {
    attrB: string;
}

type Events = (EventA | EventB)[];

const events: Events = [{ id: 1, attrA: "A" }, { id: 2, attrB: "B" }]

events.forEach(event => { // type of event is already: (parameter) event: EventA | EventB
    if (typeof event === "EventB") { // <- it doesn't work 

        const eventId = event.id // can only infer id here
    }
}) 

I’ve tried to use intersections suggested by this answer, but it does not seems to work either. What’s the right approach here?

TS playground

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since your events have differing properties, you can use in:

if ("attrA" in event) { // event is now EventA

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading