uninitialized variable works around strictNullChecks in TypeScript

96 views Asked by At

Consider this MRE:

let foo: string;
function test() {
  console.log(foo.trim())
}
test()

I am using strictNullChecks option in TSConfig. I expected the error 'foo' is possibly 'undefined' from the compiler. But I only get the one at runtime:

TypeError: Cannot read properties of undefined (reading 'trim')

Why TSConfig compiler does not complain? Why am I not required to type the uninitialized variable as string | undefined?

No compilation error here neither:

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 rather why TypeScript does not do it, I thought it was part of his job!

EDIT: As noticed by @matthieu-riegler it behaves as expected when the variable is not declared as a top-level variable. But in fact it appears it behaves as expected only when the variable is declared at the same "level" of the call site, because this also does not raise any compiler error:

function test() {
let foo: string;
  function test2() {
    console.log(foo.trim())
  }
}
test()
1

There are 1 answers

3
Matthieu Riegler On

There is an open issue on that on the Typescript repo.

This issue, while old has been discussed recently in a design meeting.

There is an open PR tol "fix" this by throwing an error when variables are used but never initialized.

Also you can notice that this is only an issue for "top-level" let variables.