# Types

⚡️ Tags: 📍Typescript

# Type vs. Interface

# Utility Types

Assume we have Todo interface

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

# Partial

Partial <Type>: Constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type.

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  return { ...todo, ...fieldsToUpdate };
}

# Required

Required <Type>: Constructs a type consisting of all properties of Type set to required. The opposite of Partial.

# Readonly

Readonly <Type>: Constructs a type with all properties of Type set to readonly, meaning the properties of the constructed type cannot be reassigned.

# Pick

Pick <Type, Keys>: Constructs a type by picking the set of properties Keys from Type.

type TodoPreview = Pick<Todo, "title" | "completed">;

# Omit

Omit <Type, Keys>: Constructs a type by picking all properties from Type and then removing Keys.

type TodoPreview = Omit<Todo, "description">;

# Record

Record <Keys, Type>: Constructs a type with a set of properties Keys of type Type. This utility can be used to map the properties of a type to another type.

interface PageInfo {
  title: string;
}

type Page = "home" | "about" | "contact";

const nav: Record<Page, PageInfo> = {
  about: { title: "about" },
  contact: { title: "contact" },
  home: { title: "home" },
};

# NonNullable

NonNullable <Type>: Constructs a type by excluding null and undefined from Type.

type T0 = NonNullable<string | number | undefined>;
//    ^ = type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;
//    ^ = type T1 = string[]

# Exclude

Exclude <Type, ExcludedUnion>: Constructs a type by excluding from Type all union members that are assignable to ExcludedUnion.

type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
//    ^ = type T1 = "c"

# Extract

Extract <Type, Union>: Constructs a type by extracting from Type all union members that are assignable to Union.

type T0 = Extract<"a" | "b" | "c", "a" | "f">;
//    ^ = type T0 = "a"

# ReturnType

ReturnType <Type>: Constructs a type consisting of the return type of function Type.

# InstanceType

InstanceType <Type>: Constructs a type consisting of the instance type of a constructor function in Type.

# References