Home > OS >  Typescript: type guard not working as expected
Typescript: type guard not working as expected

Time:08-03

type VEvent = {
    type: "VEVENT";
    summary: string;
};

type VCalendar = {
    type: "VCALENDAR";
};

const data: Record<string, VEvent | VCalendar> = (...);

array.map((id) => {
    return {
        id,
        title: data[id].type === "VEVENT" && data[id].summary,
    };
});

^ It says Property 'summary' does not exist on type 'VCalendar' even though I type-guarded data[id] is VEvent by checking data[id].type is "VEVENT"

But then I wrapped the callback with iife function and it doesn't error. No idea why this happened.

array.map((id) => ((cal: VEvent | VCalendar) => {
    return {
        id,
        title: cal.type === "VEVENT" && cal.summary,
    };
})(data[id]));

CodePudding user response:

Typescript doesn't assume that successive calls to array accessors data[id] have the same value, so you need to store it in a variable before using the inferred type, like this:

    const item = data[id]
    return {
        id,
        title: item.type === "VEVENT" && item.summary,
    };

  • Related