I encountered the following error when I wrote code using 'Optional Changing'.
type Foo = {
b?: number
}
const foo:Foo = {}
if (foo?.b) {
console.log(foo.b / 10)
}
type Foo = {
b?: number
}
const foo:Foo = {}
const flag = foo?.b
if (flag) {
// ERROR: Object is possibly 'undefined'
console.log(foo.b / 10)
}
The first code is no problem.
However, the second code will cause an error.
Why does this error occur?
Also, I would like to know how to avoid the error by writing the second code!
flagis just a variable for typescript, it 'forgets' that it is initialized fromfoo?.bfoo.b! / 10to inform ts thatfoo.bwill be defined at that time