DEV Community

Lam
Lam

Posted on

Typescript Cheat Sheet

Type extraction

interface Building {
  room: {
    door: string,
    walls: string[],
  };
}

type Walls = Building['room']['walls']; // string[]
Enter fullscreen mode Exit fullscreen mode

Modules

export interface User { ... }
Enter fullscreen mode Exit fullscreen mode

Generics

class Greeter<T> {
  greeting: T
  constructor(message: T) {
    this.greeting = message
  }
}

let greeter = new Greeter<string>('Hello, world')
Enter fullscreen mode Exit fullscreen mode

Classes

class Point {
  x: number
  y: number
  static instances = 0
  constructor(x: number, y: number) {
    this.x = x
    this.y = y
  }
}
Enter fullscreen mode Exit fullscreen mode

Inheritance

class Point {...}

class Point3D extends Point {...}

interface Colored {...}

class Pixel extends Point implements Colored {...}
Enter fullscreen mode Exit fullscreen mode

Short fields initialisation

class Point {
  static instances = 0;
  constructor(
    public x: number,
    public y: number,
  ){}
}
Enter fullscreen mode Exit fullscreen mode

Fields which do not require initialisation

class Point {
  public someUselessValue!: number;
  ...
}
Enter fullscreen mode Exit fullscreen mode

Function types

interface User { ... }

function getUser(callback: (user: User) => any) { callback({...}) }

getUser(function (user: User) { ... })
Enter fullscreen mode Exit fullscreen mode

Type aliases

type Name = string | string[]
Enter fullscreen mode Exit fullscreen mode

[Interfaces] Dynamic keys

{
  [key: string]: Object[]
}
Enter fullscreen mode Exit fullscreen mode

[Interfaces] Read only

interface User {
  readonly name: string
}
Enter fullscreen mode Exit fullscreen mode

[Interfaces] Optional properties

interface User {
  name: string,
  age?: number
}
Enter fullscreen mode Exit fullscreen mode

[Interfaces] Explicit

interface LabelOptions {
  label: string
}

function printLabel(options: LabelOptions) { ... }
Enter fullscreen mode Exit fullscreen mode

Reference

Top comments (1)

Collapse
 
lyrod profile image
Lyrod

For Generics, in this example, specifying is useless because TypeScript will infer it