Here is an example of some TypeScript code:
let foo: string;
function test() {
console.log(foo.trim())
}
test()
I have enabled the strictNullChecks
option in TSConfig.
I was expecting the compiler to raise the error 'foo' is possibly 'undefined'
.
However, I only encounter this error at runtime:
TypeError: Cannot read properties of undefined (reading 'trim')
Why doesn't the TSConfig compiler give me a warning?
Why am I not prompted to define the uninitialized variable as string | undefined
?
There are no compilation errors here either:
module1
export let foo: string;
module2
import { foo } from 'module1';
console.log(foo.trim());
I know how to enforce type checking for undefined
, but my question is why doesn't TypeScript handle it automatically? Isn't that part of its job?
EDIT: As pointed out by @matthieu-riegler, it works as expected when the variable is not declared as a top-level variable. But interestingly, it seems that it behaves correctly only when the variable is declared at the same "level" as the call site, as shown in this example without any compiler errors raised:
function test() {
let foo: string;
function test2() {
console.log(foo.trim())
}
}
test()