Variables
In TypeScript, besides being typed, variables are expected to follow the same rules and guidelines that they do with JavaScript.
Syntax
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 string
:
let scary = 'skeletons';scary = 10.31;// Error: Type 'number' is not assignable to type 'string'
Contribute to Docs
- 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.
Learn TypeScript on Codecademy
- Career path
Full-Stack Engineer
A full-stack engineer can get a project done from start to finish, back-end to front-end.Includes 51 CoursesWith Professional CertificationBeginner Friendly150 hours - Free course
Learn TypeScript
Learn TypeScript, a superset of JavaScript that adds types to make the language scale!Intermediate10 hours