Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Object is possibly 'undefined'. ts(2532)" after I just defined it

Tags:

typescript

TypeScript is throwing Object is possibly 'undefined'. ts(2532) errors for an optional parameter, even though I just defined it...

interface Foo {
  keyValue?: Record<string, string>
}

const a: Foo = { keyValue: { key1: 'value' } }
a.keyValue.key2 = 'value2' // Object is possibly 'undefined'. ts(2532)

const b: Foo = {}
b.keyValue = { key1: 'value' }
b.keyValue.key2 = 'value2' // Works fine

Why does a.keyValue throw the error when b.keyValue doesn't? The only difference is slightly more verbose syntax.

like image 417
Adam Biggs Avatar asked Oct 29 '25 19:10

Adam Biggs


1 Answers

By doing : Foo, you're telling TypeScript that the type that the variable contains is exactly Foo - and in Foo, the property is optional.

const a: Foo = { keyValue: { key1: 'value' } }

is, to TypeScript, a bit like

declare const a: Foo;

The fact that the object on the right-hand side does really have the property is lost when you say that it's actually Foo, where the property is optional.

But with

const b: Foo = {}
// at this point, b is Foo exactly
b.keyValue = { key1: 'value' }
// at this point, b is no longer exactly Foo; it also definitely has the keyValue property

The property is assigned after the variable is declared to be of type Foo - so TypeScript is able to see the line that assigns to the property and conclude that it definitely exists. (making the shape of b slightly different from the original Foo, where the property is optional).

like image 163
CertainPerformance Avatar answered Nov 01 '25 13:11

CertainPerformance