Home > Mobile >  How to narrow union types in array with typescript?
How to narrow union types in array with typescript?

Time:10-20

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

CodePudding user response:

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

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

Playground

  • Related