Closed
Description
TypeScript Version:
When using --strictNullChecks with any of these versions:
- 2.0
- 2.7.2
- 2.8.0-dev.20180222 (typescript@next)
Search Terms:
- TS2345
- type guard
- strictNullChecks
Code
in a file tsc-bug.ts:
function asString(): string | undefined {
return undefined
}
function g(a: string) {
return
}
function f() {
let a = asString() // intellisense correctly shows a is of type string | undefined
if (a) { // more explicit guard also fails: if (typeof a === "string")
let ar = [1,2,3]
g(a) // after the type guard "if (a)", intellisense correctly shows a is of type string
ar.forEach((x) => {
// tsc 2.7.2 outputs: error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
// also tsc 2.0 and 2.8.0-dev.20180222
g(a) // ERROR: intellisense incorrectly shows a is of type string | undefined
})
}
}
Expected behavior:
When using the compiler option: --strictNullChecks
Expect second call of g(a) to be treated the same as the first call.
Both are in the same scope.
Actual behavior:
Second call to g(a) somehow loses track of the type restriction imposed by the guard.
The compiler issues this error:
tsc-bug.ts(18,15): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Related Issues: