Data Type |
Description |
Examples |
boolean
|
logical values:
true or
false.
|
let active: boolean = false;
let enabled: boolean = true;
|
number
|
floating point values. (decimal, hexadecimal, binary, octal)
|
let x: number = 5;
let y: number = 1.5;
let z: number = Math.PI;
|
string
|
textual data
|
let message: string = "hello";
let x: number = 5;
let fullMessage: String = `message number: ${x}, ${message}`;
console.log(fullMessage);
message number: 5, hello
|
Arrays
|
Either [] or <> is used.
|
let evens: Array<number> = [2, 4, 6];
let odds: number[] = [1,3,5];
|
Tuple
|
Array of different types
|
let myData: [string, number] = ["hi", 5]; //tuple
myData.forEach((value, index) => {
console.log(`val: ${value}, index: ${index} type: ${typeof value}`);
});
val: hi, index: 0 type: string
val: 5, index: 1 type: number
|
enum
|
Enumerated constants
|
enum Food {Pasta, Rice};
console.log(Food.Pasta);
console.log(Food.Rice);
console.log(Food[1]);
let x: Food = Food.Rice;
console.log(x);
0
1
Pasta
1
Manual numbering:
enum Food {Pasta=3, Rice=5};
console.log(Food.Pasta);
console.log(Food.Rice);
3
5
This is also possible:
enum Food {Pasta='one', Rice='two'};
console.log(Food.Pasta);
console.log(Food.Rice);
one
two
|
Any
|
assignable to any type
|
let x : any = "a string";
console.log(typeof x)
x = 2;
console.log(typeof x)
x = true;
console.log(typeof x)
string
number
boolean
|
void
|
return type of a function which returns nothing
|
function showSquare(x: number): void{
console.log(x*x);
}
showSquare(6);
36
|
Object
|
type of an object instance
|
TypeScript support class syntax similar to ES6 class:
class Shape{
draw(){
console.log("drawing shape");
}
}
let shapeInstance: Shape = new Shape();
shapeInstance.draw();
drawing shape
|
null
|
type of null literal
|
let x: null = null;
//other types can be assigned to null
let y: string = null;
|
undefined
|
type of undefined literal
|
let x: undefined = undefined;
//other types can be assigned to undefined
let y: string = undefined;
|
never
|
return type of a function that never returns
|
function doSomething(message: string): never {
throw new Error(message);
}
|