#Null narrowing doesn't work with Record and key as variable?

22 messages · Page 1 of 1 (latest)

undone valley
#
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

Am I doing something wrong here? Am I supposed to use a non-null assertion or is this a bug in the type narrowing?

brittle pawn
#

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

#

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

undone valley
#

Hmmmm

brittle pawn
#

what you can do is assign foo[key] to a variable
can will then be narrowed by the if

undone valley
#

I should have checked in the playground... it seems this was fixed (or design changed) around TS4.7.4

fervent lintelBOT
#
Aaron#7246

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```

undone valley
#

I'm using 4.4.3 currently... need to update!

brittle pawn
#

true

undone valley
#

To be clear, in 4.7.4 this works:

const key = "red"
if (foo[key]) foo[key].type
brittle pawn
#

righ, what I described was the old behavior

brittle pawn
#

!resolved