Having reviewed this particular question, my current focus is on understanding how variables can be narrowed down using control flow. An example:
type T1 = {
a?: {
b: string
}
}
const t1: T1 = {}
t1.a.b // displays error, possibly undefined
t1.a = { b: "foo" }
t1.a.b // now works as expected, TypeScript recognizes property a exists
The specific scenario I am struggling with at the moment:
const t1: T1 = {}
t1.a = { b: "foo" }
function foo(t: T1) {
t.a = undefined
}
foo(t1) // function foo changes prop "a" back to undefined
// t1.a = undefined ; this should generate an error
console.log(t1.a.b) // ... "a" is still considered defined here and TS compiles successfully :/
// This will result in a runtime error.
I would anticipate TypeScript to acknowledge that foo
manipulates the mutable value t1
(properties in T1
do not have the readonly
flag). foo
could potentially alter the value (which it does in this case), so the compiler should reset all previous narrowing types of t1
and report a
in console.log(t1.a.b)
as possibly undefined
once again.
My inquiry now is: How intricate is this control flow mechanism and what rules does it adhere to in the above example? You can also view the code in action through this link. Thank you!