-
Notifications
You must be signed in to change notification settings - Fork 763
Description
Expected Behavior:
When using type guards like Array.isArray or truthiness checks in an if block, the type of the variable within that block should be narrowed down to the more specific type.
For Array.isArray(foo):
const foo: string | string[] = 'foo'; // or ['foo']
if (Array.isArray(foo)) {
// foo should be inferred as string[]
foo;
}For truthiness check on bar:
const bar: string | undefined = 'bar'; // or undefined
if (bar) {
// bar should be inferred as string
bar;
}Actual Behavior:
The type of the variable inside the if block is not being narrowed correctly.
For Array.isArray(foo):
const foo: string | string[] = 'foo'; // or string[]
if (Array.isArray(foo)) {
// foo is inferred as string | string[]
foo;
}The type of foo remains string | string[] inside the if block, even after the Array.isArray(foo) check.
For truthiness check on bar:
const bar: string | undefined = 'bar'; // or undefined
if (bar) {
// bar is inferred as string | undefined
bar.charAt(0); // Error: Object is possibly 'undefined'.
}The type of bar remains string | undefined inside the if block, even after the truthiness check. This can lead to unnecessary errors or require explicit type assertions.
Additional Context:
@typescript/native-preview: "7.0.0-dev.20250522.2"
TypeScript (Native Preview): 0.20250522.2