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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With