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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (1)

Collapse
 
lyrod profile image
Lyrod •

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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more