TypeScript is just like ES2015 with type-checking. All ES2015 (classes, etc) should work.
Basic types
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| any void
boolean number string
null undefined
string[] [string, number]
string | null | undefined
never
|
1 2
| enum Color {Red, Green, Blue = 4} let c: Color = Color.Green
|
Declarations
1 2
| let isDone: boolean let isDone: boolean = false
|
1 2 3 4 5 6
| function add (a: number, b: number): number { return a + b }
function add (a: number, b: number) { ... }
|
Type assertions
Variables
1 2
| let len: number = (input as string).length let len: number = (<string> input).length
|
Functions
1 2 3 4 5 6 7 8 9
| function object(this: {a: number, b: number}, a: number, b: number) { this.a = a; this.b = b; return this; }
let a = object(1,2);
|
Interfaces
Inline
1 2 3 4 5 6 7
| function printLabel (options: { label: string }) { console.log(options.label) }
function getUser (): { name: string; age?: number } { }
|
Explicit
1 2 3 4 5
| interface LabelOptions { label: string }
function printLabel(options: LabelOptions) { ... }
|
Optional properties
1 2 3 4
| interface User { name: string, age?: number }
|
Read only
1 2 3
| interface User { readonly name: string }
|
Dynamic keys
1 2 3
| { [key: string]: Object[] }
|
Type aliases
1
| type Name = string | string[]
|
Function types
1 2 3 4 5
| interface User { ... }
function getUser(callback: (user: User) => any) { callback({...}) }
getUser(function (user: User) { ... })
|
Classes
1 2 3 4 5 6 7 8 9
| class Point { x: number y: number static instances = 0 constructor(x: number, y: number) { this.x = x this.y = y } }
|
Inheritance
1 2 3 4 5 6 7
| class Point {...}
class Point3D extends Point {...}
interface Colored {...}
class Pixel extends Point implements Colored {...}
|
Short fields initialisation
1 2 3 4 5 6 7
| class Point { static instances = 0; constructor( public x: number, public y: number, ){} }
|
Fields which do not require initialisation
1 2 3 4
| class Point { public someUselessValue!: number; ... }
|
Generics
1 2 3 4 5 6 7 8
| class Greeter<T> { greeting: T constructor(message: T) { this.greeting = message } }
let greeter = new Greeter<string>('Hello, world')
|
Modules
1
| export interface User { ... }
|
1 2 3 4 5 6 7 8
| interface Building { room: { door: string, walls: string[], }; }
type Walls = Building['room']['walls'];
|