#Why can this value be undefined?

9 messages · Page 1 of 1 (latest)

quick stone
#

Is the typeguard not enough? invoiceData.defaultTax in myObj also doesn't work (found on StackOverflow)

export const TaxTypes = ["AL", "BC", "NB", "NL", "NS", "ON", "EXEMPT"] as const;

export type TaxType = (typeof TaxTypes)[number];

export const TaxRate: Record<TaxType, number> = {
    AL: 0.05,
    BC: 0.05,
    NB: 0.05,
    NL: 0.15,
    NS: 0.15,
    ON: 0.13,
    EXEMPT: 0,
};

type Invoice = {
    defaultTax: TaxType;
};

const invoiceData: Invoice = { defaultTax: "ON" };

const myObj: Partial<Record<TaxType, number>> = {};

for (const taxType of TaxTypes) {
    if (taxType === "AL") {
        myObj[taxType] = 100;
        console.log("Object", myObj);
    }
}

const testOne = invoiceData.defaultTax + 50;
console.log(testOne);

if (myObj[invoiceData.defaultTax] !== undefined) {
    const testTwo = myObj[invoiceData.defaultTax] + 25;
    console.log(testOne, testTwo);
}
agile stirrup
#

Since defaultTax property is mutable, TS assumes that it might change between the condition check and its usage in the addition expression

#

You can get around it by reading it to a variable and using that in those places

#

@quick stone

gusty carbon
#

You're also using Partial lol which makes every value optional, aka possibly undefined.

#

So instead of doing myObj: Record<...>, you can just do this: ```ts
const myObj = {} as Record<TaxType, number>;

quick stone
toxic tiger
#

@quick stone I wouldn't do that, no - that's going to unsafely assume that all the possible TaxType keys are defined, when they aren't.