#Null narrowing doesn't work with Record and key as variable?
22 messages · Page 1 of 1 (latest)
you're not supposed to use a non-null assertion
and it's not a bug either
the check you performed simply doesn't carry over in that situation
and it is by design
Understand how TypeScript uses JavaScript knowledge to reduce the amount of type syntax in your projects.
you'll see the check is performed on a variable
that way, TS knows the variable isn't falsy/nullish
but that doesn't work when accessing an attribute
since the check doesn't narrow any variable
foo can't be narrowed
neither can key
it's the combination of the 2 that is unique
Hmmmm
what you can do is assign foo[key] to a variable
can will then be narrowed by the if
I should have checked in the playground... it seems this was fixed (or design changed) around TS4.7.4
Preview:```ts
declare const foo: Record<
string,
{type: any} | undefined
const key = "red"
if (foo[key]) foo[key].type // Error: Object is possibly 'undefined'
if (foo["red"]) foo["red"].type // Works```
I'm using 4.4.3 currently... need to update!
true
To be clear, in 4.7.4 this works:
const key = "red"
if (foo[key]) foo[key].type
righ, what I described was the old behavior
!resolved