Skip to main content

Typescript

Types

Usually when defining types, you would want to create your own types file

types.ts

<prefix>.types.ts or <prefix>_types.ts

Tips and Tricks

TODO

Array

Start by defining an array (as constant) to be able to extract the type afterwards.

const my_items = ["apple", "banana", "orange"] as const
type MyItemsType = typeof my_items[number]

MyItemsType will now be of type "apple" | "banana" | "orange".

Object typing and sub-object

type my_object = {
  a: string
  age?: number;
  readonly id: number;
}

Combining types:

type my_combined = my_object & {
  b: string
}

Union types:

type User =
  | { name: string; isAdmin: true }
  | { name: string; isAdmin: false; guestId: number }

type User =
  | { kind: "admin"; name: string }
  | { kind: "guest"; name: string; guestId: number };
Partial<T>: Makes all properties optional.
Required<T>: Makes all properties required.
Readonly<T>: Makes all properties readonly.
Pick<T, K>: Selects specific properties.
Omit<T, K>: Excludes specific properties.