What type of null/undefined is inferred?

Viewed 97

environment:

VS Code Version: 1.47.3
tsc Version: 4.0.0-dev.20200727
tsconfig.js: "strict": true,

code:

let x = null; // x is any type
let y = x; // x is null type(why? x is any type on top), y is null type

x = 1; // x is any type
y = 1; // error, y is null type

Is that normal? What type of x is inferred? I am confused

1 Answers

This has to do with this PR which introduces control flow analysis (CFA) for variables implicitly typed as any

In the example above, x and y implicitly have declared types of any but control flow analysis can determine their actual types at every reference. Therefore, no errors are reported even when the example is compiled with --noImplicitAny.

This analysis only kicks in for

[...] let and var variables that have no type annotation and either no initial value or an initial value of null or undefined.

So let's see what happens in your example:

// x is implicitly any, with null assigned, so this new CFA analysis kicks in 
let x = null; 
// for x, based on the assignment on the previous line, x is known to be null
// y typed based on the type of x, so y has type null. 
// No special CFA is triggered for y since it is not assigned the null literal value
let y = x; 

// x can be assigned any type, since it has no type annotation, so number is fine
x = 1;

// y was actually given a type when it was declared, the null type, so you can't assign number
y = 1;

// x is now number based on previous assignments
x.toExponential()

When x is the target of an assignment, it behaves as any, allowing any type to be assigned to it. When it is used in an expression, it's type will be determined based on previous assignments.

Related