TypeScript variables are generally inferred to be whatever basic type of value they are initially assigned with. Later in code, only values that are of that same basic type may be assigned to the variable. The term for whether a type is assignable to another type is assignability.
let myVar: string;myVar = 'Hello'; // OkmyVar = 'World!'; // Also OkmyVar = 42; // Not Ok: Type 'number' is not assignable to type 'string'.
Examples with Variables
In this snippet of code, TypeScript sees that the
spooky variable is initially assigned a
boolean value, so it believes the
spooky variable should always be of type
boolean. Assigning a variable of type
boolean later on is allowed, as a type is assignable to itself:
let spooky = true;spooky = false; // Ok
If a variable is assigned a different type of value, TypeScript will notice and emit a type checking complaint. Those type checking complaints can be surfaced as:
- Errors on the command-line.
- Syntax highlights in the code editor.
In this code snippet, the
scary variable is initially assigned the value
"skeletons", which is a
string type. Later, assigning the decimal number
10.31 is not allowed because a
number type is not assignable to a variable of type
let scary = 'skeletons';scary = 10.31;// Error: Type 'number' is not assignable to type 'string'
- Anonymous contributorAnonymous contributor85 contributions
- Anonymous contributor
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.