DEV Community

Lam
Lam

Posted on

3 3

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
lyrod profile image
Lyrod

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay