TypeScript
Feature
Basic Type
boolean
false and true.
let a: boolean = false;
number
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
string
let color: string = "blue";
color = 'red';
array
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
tuple
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error
enum
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
any
let isDone: any = false;
isDone.ifItExists()
Why we need any? Would not specifying any word works? No. If without any the compiler shows that ifItExists is not a method of isDone.
This is a kind of compatible design? To get people comfortable.
void
It's like the opposite of any, that the variable cannot have any type. Useful in function return value.
function warnUser(): void {
console.log("This is my warning message");
}
let a: void = 1; //error
let a: void = undefined; //pass
undefined & null
These two are actually a type???
It's in advanced topic chapter.
never
Never be assigned.
let a:never;
a = 2; // wrong
It's useful in function return type
// Function returning never must have unreachable end point
function error(message: string): never {
throw new Error(message);
}
object
Representing non-primitive type
Type Inference