Open
Description
Search: Object is possibly null, narrowed type, type constraint, closure
Code
const foo: string | null = 'bar'
if (foo) {
function baz() {
console.log(foo.length) // Object is possibly 'null'
}
}
Expected behavior:
Compiles
Actual behavior:
const foo: string | null
Object is possibly 'null'
Playground Link:
Related Issues:
Discussion:
By design, type narrowings are reset inside closures. This makes sense, but there is one case where better assumptions can be made: when the closure is defined inside a type constraint block AND the type narrowing is based on a const
value. Even if called from async, the closure is still referencing a const and was created after a suitable type constraint occurred.
Thoughts?