TypeScript Inference
This lesson describes how TypeScript infers types when we omit to explicitly provide one.
We'll cover the following...
Control flow analysis
Since version 2.0, TypeScript checks the type of all possible flows. This means that TypeScript analyzes all paths to discover the most specific type a variable can be. In other words, if you define a variable to be many types, with a union |
, TypeScript knows, line by line, what the actual type of the variable is. This is useful to get code to completion.
Code completion is when the developer types and the editor is suggesting functions or properties available. Good code completion editors provide useful possible code depending on the type.
let manyTypes: string | number;manyTypes = "Line #2 is a string";console.log(manyTypes.length); // Line 3 is a string, "length" is accessiblemanyTypes = 100;
The code above shows that the variable has a dual-type of string
or number
. The declaration on line 1 uses the pipe (|
) symbol to have the manyTypes
variable accept a string
or a number
.
During the flow of execution, the variable is actually first a string
on line 2 and then a number
on line 4, never both.