×
☰ See All Chapters

Typescript Variables

Variable is a reference for a value. In javaScript variables are declared using var keyword, In TypeScript, variable declarations can be done by using with let or const keywords also. In JavaScript we cannot specify variable’s type. TypeScript's primary characteristic is the ability to specify a variable's type in its declaration. A variable's type can be a predefined TypeScript type or a custom type. When the code is compiled into JavaScript, its type specifications disappear.

typescript-variables-0
 

TypeScript syntax of declaring a variable with type

 

 

Syntax

Example

Variable declaration

var variableName: variableType;

let variableName: variableType;

var xyz: number;

let xyz: number;

Variable declaration and initialization

var variableName: variableType = variableValue;

let variableName: variableType = variableValue;

const variableName: variableType = variableValue;

var xyz: number = 3;

let xyz: number = 3;

const xyz: number = 3;

 

const variables declaration and initialization cannot be done in separate line. Only let and var variables can be declared and initialized in separate lines.

typescript-variables-1
 

if a variable is declared with const, its value is expected to remain constant throughout the block. Any attempt to change the variable's value will result in a compiler error.

typescript-variables-2
 

Type inference

Specifying type of variable is optional.  When an untyped variable is initialized, the compiler automatically sets the variable's type to that of the value. This is called type inference in TypeScript. Therefore, if a variable is initialized to a value, there's no need to define its type.

 typescript-variables-3
 

In the first line x is assined a value 5 which is number type. Compiler automatically sets the  x’s type to number. So in the next line x is assigned a String value which is an error.

If a variable isn't initialized in its declaration, then it's important to provide its type.

 

       

 

                   


All Chapters
Author