Search code examples
typescriptundefined

TypeScript: Object is possibly 'undefined'. after conditional creation on object with optional, well-defined keys


I have this code

type t = "a" | "b"
const o: { [key in t]?: Array<number> } = {}
interface Thing {
    t: t;
}
const things: Array<Thing> = [{ t: "a"}]
for (const thing of things ) {
    if (!(thing.t in o)) o[thing.t] = []
    o[thing.t].push(1)
}

And get the error Object is possibly 'undefined'.

TS Playground link


Solution

  • The way is to

    for (const thing of things) {
        ; (o[thing.t] ??= []).push(1)
    }