Skip to content

Instantly share code, notes, and snippets.

@navix
Last active February 4, 2023 18:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navix/4fc760af9d6c9b8e0bc0035779854e7c to your computer and use it in GitHub Desktop.
Save navix/4fc760af9d6c9b8e0bc0035779854e7c to your computer and use it in GitHub Desktop.
Typescript advanced built-in types

Typescript advanced built-in types (utility types)

Official documentation: https://www.typescriptlang.org/docs/handbook/utility-types.html

Partial

Make all properties in T optional.

type t = Partial<{a: string; b: number}>;
// {a?: string; b?: number}

Required

Make all properties in T required.

type t = Required<{a?: string; b?: number}>;
// {a: string; b: number}

Readonly

Make all properties in T readonly.

type t = Readonly<{a: string; b: number; c?: boolean}>;
// {readonly a: string; readonly b: number; readonly c?: boolean}

Pick

From T, pick a set of properties whose keys are in the union K.

type t = Pick<{a: string; b: number; c?; boolean}, 'a' | 'c'>;
// {a: string; c?; boolean}

Record

Construct a type with a set of properties K of type T.

type Demo = {...};
type t = Record<'a' | 'b' | 'c', Demo>;
// {a: Demo; b: Demo; c: Demo}

Exclude

Exclude from T those types that are assignable to U.

type t = Exclude<'a' | 'b' | 'c' | 'd', 'b' | 'c' | 'x' | 'y'>;
// 'a' | 'd'

Extract

Extract from T those types that are assignable to U.

type t = Extract<'a' | 'b' | 'c' | 'd', 'b' | 'c' | 'x' | 'y'>;
// 'b' | 'c'

NonNullable

Exclude null and undefined from T.

type t = NonNullable<'a' | string | number | undefined>;
// 'a' | string | number

Parameters

Obtain the parameters of a function type in a tuple.

type t = Parameters<(a: string, b: number) => void>;
// [string, number]

ReturnType

Obtain the return type of a function type.

type t = ReturnType<(a: string, b: number) => string>;
// string

InstanceType

Obtain the return type of a constructor function type.

More info: microsoft/TypeScript#25998 (comment)

type t = InstanceType<typeof C>;
// C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment