Skip to content

Utility Types#

Partial#

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

const p: Partial<User> = { name: "Alice" }; // age is optional

Required#

interface Props { limit?: number; }

const r: Required<Props> = { limit: 10 }; // limit is required

Readonly#

interface Config { apiUrl: string; }

const c: Readonly<Config> = { apiUrl: "" };
// c.apiUrl = "new"; // Error

Pick#

interface Task { id: number; title: string; completed: boolean; }

type TaskInfo = Pick<Task, "title" | "completed">;

Omit#

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

type UserInput = Omit<User, "id">;

Record#

type Roles = "admin" | "user";

const permissions: Record<Roles, number> = {
  admin: 1,
  user: 0
};

Exclude#

type Status = "success" | "error" | "loading";

type NonLoading = Exclude<Status, "loading">; // "success" | "error"

Extract#

type Event = "click" | "scroll" | "mousemove";

type MouseEvent = Extract<Event, "mousemove" | "click">;

NonNullable#

type Name = string | null | undefined;

type SafeName = NonNullable<Name>; // string

ReturnType#

function getUser() { return { name: "Alice", age: 30 }; }

type User = ReturnType<typeof getUser>;

Parameters#

function add(a: number, b: number) {}

type Args = Parameters<typeof add>; // [number, number]

ConstructorParameters#

class Person { constructor(name: string) {} }

type Params = ConstructorParameters<typeof Person>; // [string]

InstanceType#

class Car {}

type C = InstanceType<typeof Car>; // Car

Awaited#

async function getData() { return "data"; }

type Data = Awaited<ReturnType<typeof getData>>; // string

String Manipulation Types#

type U = Uppercase<"hello">;      // "HELLO"
type L = Lowercase<"WORLD">;      // "world"
type C = Capitalize<"hello">;     // "Hello"
type UC = Uncapitalize<"Hello">;  // "hello"