Closed
Description
TypeScript Version:
1.9.0-dev.20160528-1.0
Code
function printString() {
const myString: string|null = 'Hello';
if (myString == null) {
return;
}
setTimeout(() => {
console.log('String length was ' + myString.length);
}, 100);
}
printString();
Actual behavior:
When compiled with --strictNullChecks
, this code fails:
testcase.ts(7,44): error TS2531: Object is possibly 'null'.
Expected behavior:
Null inference works fine within the immediate printString
scope, but it's disabled inside closures.
This behavior makes sense for variables, since otherwise I could write something like this, that would make myString
actually become null when it's read and fail:
function printString() {
let myString: string|null = 'Hello';
if (myString == null) {
return;
}
setTimeout(() => {
console.log('String length was ' + myString.length);
}, 100);
myString = null;
}
printString();
On the other hand, constants don't allow this, so their non-nullity can be guaranteed if they were checked before the closure was declared.