(TypeScript) Utility Types

·

2 min read

Exclude<UnionType, ExcludedMembers>

The second argument type gets excluded from the first argument type.

type T1 = string | number | boolean;
type T2 = Exclude<T1, string>;

// okay
const a: T2 = 1;
// not okay
const b: T2 = '1';

Pick<Type, Keys>

It is using just several properties in an object type.

interface User {
  id: number;
  name: string;
  age: number;
  gender: 'm' | 'w';
}

// okay
const user1: Pick<User, 'id' | 'name'> = {
  id: 1,
  name: 'Bada1',
};

// not okay, because of 'age'
const user2: Pick<User, 'id' | 'name'> = {
  id: 2,
  name: 'Bada2',
  age: 30,
};

Omit<Type, Keys>

Contrary to 'Pick', it is not using several properties in an object type.

interface User {
  id: number;
  name: string;
  age: number;
  gender: 'm' | 'w';
}

// okay
const user1: Omit<User, 'id' | 'name'> = {
  age: 30,
  gender: 'w',
};

// not okay, because of 'id'
const user2: Omit<User, 'id' | 'name'> = {
  id: 2,
  age: 30,
  gender: 'w',
};

Record<Keys, Type>

The former argument becomes the keys of the object, and the letter one becomes the types of the values.

Unlike index signature, we can designate specific properties.

type Key = 'id' | 'name' | 'age';
type Value = string | number;

// okay
let user1: Record<Key, Value> = {
  id: 1,
  name: 'Bada1',
  age: 30,
};

// not okay, because there is no 'age'
let user2: Record<Key, Value> = {
  id: 2,
  name: 'Bada2',
};

// not okay, becaue the value of 'age' is a boolean
let user3: Record<Key, Value> = {
  id: 3,
  name: 'Bada3',
  age: false,
};

Partial<Type>

It makes all the properties in an object optional.

interface User {
  id: number;
  name: string;
  age: number;
  gender: 'm' | 'f';
}

// okay
let user1: Partial<User> = {
  id: 1,
  name: 'Bada',
};

Required<Type>

It makes all the properties should be used, even if there are optional properties.

interface User {
  id: number;
  name: string;
  age?: number;
  gender?: 'm' | 'f';
}

// not okay
let user1: Required<User> = {
  id: 1,
  name: 'Bada',
};

Readonly<Type>

Properties in an object cannot be reassigned.

interface User {
  id: number;
  name: string;
}

let user1: Readonly<User> = {
  id: 1,
  name: 'Bada',
};

// not okay
user1.id = 2;

NonNullable<Type>

It excludes 'undefined' and 'null' from the argument type.

type T1 = string | undefined | null;
type T2 = NonNullable<T1>;

// okay
const a: T2 = '';
// not okay
const b: T2 = undefined;
// not okay
const c: T2 = null;