Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript Nullish coalescing

Tags:

typescript

I don't understand why typescript gives me a WARNING for a code like the below-mentioned one. the generated code works as expected, but typescript complains that key1 doesn't exist on one of the objects. I mean that's true whereas that's what the ?? Is there some ways I can write it differently?

const foobar = {
    foo: { key1: 2 },
    bar: { key2: 2 }
}


function getValue(someKey: keyof typeof foobar){
    return foobar[someKey].key1 ?? 0
}

Playground

like image 886
L.A Avatar asked Jun 18 '26 23:06

L.A


1 Answers

The nullish coalescing in your example happens after the type error. You're trying to use key1 on a type that may or may not have it. foobar[someKey] has the type { key1: number; } | { key2: number; }. Since someKey may be "bar", key1 may not exist. You need a guard to differentiate between the type with key1 and the type with key2 before you can use either of those in the function. (And then there's no need for nullish coalescing, since you know that key1 isn't null or undefined.)

For instance:

function getValue(someKey: keyof typeof foobar){
    const obj = foobar[someKey];
    return "key1" in obj ? obj.key1 : 0;
}

Playground link

Or to avoid the in operation (I'm sometimes guilty of premature micro-optimization):

function getValue(someKey: keyof typeof foobar){
    return someKey === "foo" ? foobar.foo.key1 : 0;
}

Playground link

Remember that telling you when you try to use a property on an object when that object's type doesn't define a property with that name is one of TypeScript's primary jobs. That's what it's doing with the error on your original code.

like image 199
T.J. Crowder Avatar answered Jun 20 '26 22:06

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!