Closed
Description
Bug Report
π Search Terms
typeof, type guard, undefined guard, loop
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about Type System Behaviour and Type Guards
β― Playground Link
π» Code
interface IProperties {
foo?: {
aaa: string
bbb: string
}
}
function init(properties: IProperties) {
if (properties.foo) {
type FooOK = typeof properties.foo;
properties.foo; // type is { aaa: string; bbb: string; }
for (const x of [1, 2, 3]) {
properties.foo; // type is { aaa: string; bbb: string; }
type FooOrUndefined = typeof properties.foo; //type is { aaa: string; bbb: string; } | undefined
}
}
}
π Actual behavior
Under a loop nested in undefined type guard for variable properties.foo
,
properties.foo
is inferred to be{ aaa: string; bbb: string; }
typeof properties.foo
is inferred to{ aaa: string; bbb: string; } | undefined
This happens both for for...of and while loops.
π Expected behavior
typeof takes type guard into account:
typeof properties.foo
is inferred to{ aaa: string; bbb: string; }