Variable is the name of reserved memory location. It means when we declare a variable some part of memory is reserved.
Rules for declaring a TypeScript variable:
- TypeScript variable name must begin with a letter, underscore, or dollar sign.
- TypeScript variable names are case sensitive.
- TypeScript reserved keywords like abstract, boolean etc can’t be used as TypeScript variable name.
Variable Declaration in TypeScript
TypeScript provides the following 4 ways to declare a variable. Common syntax for a variable declaration is to include a colon (:) after the variable name which followed by its type. We can use var or let keyword to declare a variable.
- Declare a variable with type and value.
By using var keyword:
var variableName:data_type = value;
By using let keyword:
let variableName:data_type = value;
- Declare a variable with type but no value. Variable’s value will be set to undefined by default.
By using var keyword:
var variableName:data_type;
By using let keyword:
let variableName:data_type;
- Declare a variable with value but no type. Variable’s type will be set to any by default.
By using var keyword:
var variableName = value;
By using let keyword:
let variableName = value;
- Declare a variable without type and value. Variable’s type will be set to any and value will be set to undefined by default.
By using var keyword:
var variableName;
By using let keyword:
let variableName;