Back to Home
Published: Sun Aug 25 2024EN
Table of Contents

Built-in Utility Types

TypeScript provides several built-in utility types to facilitate common type transformations. These utilities help manipulate types without needing to write complex type logic from scratch, improving code readability and maintainability.

Utility Type Description Example Usage
Partial<T> Constructs a type with all properties of T set to optional. Useful for update operations or default values. interface User { id: number; name: string; } type UpdateUserDto = Partial<User>; // { id?: number; name?: string; }
Required<T> Constructs a type consisting of all properties of T set to required. Useful when you need to ensure all properties are present. interface Props { a?: number; b?: string; } type RequiredProps = Required<Props>; // { a: number; b: string; }
Readonly<T> Constructs a type with all properties of T set to readonly. Useful for representing immutable data structures. interface Config { apiKey: string; } const config: Readonly<Config> = { apiKey: "..." }; // config.apiKey = "new"; // Error
Record<K, T> Constructs an object type whose property keys are K and whose property values are T. Useful for dictionaries or maps. type PageInfo = { title: string; }; type Pages = Record<'home' \| 'about', PageInfo>; // { home: PageInfo; about: PageInfo; }
Pick<T, K> Constructs a type by picking the set of properties K (string literal or union of string literals) from T. Useful for creating smaller types from larger ones. interface User { id: number; name: string; email: string; } type UserPreview = Pick<User, 'id' \| 'name'>; // { id: number; name: string; }
Omit<T, K> Constructs a type by picking all properties from T and then removing K. Useful for excluding sensitive or unnecessary fields. interface User { id: number; name: string; password?: string; } type PublicUser = Omit<User, 'password'>; // { id: number; name: string; }
Exclude<T, U> Constructs a type by excluding from T all union members that are assignable to U. Useful for filtering union types. type Status = 'success' \| 'error' \| 'loading'; type NonLoadingStatus = Exclude<Status, 'loading'>; // 'success' \| 'error'
Extract<T, U> Constructs a type by extracting from T all union members that are assignable to U. Useful for selecting specific members from a union. type Shape = { kind: 'circle'; radius: number; } \| { kind: 'square'; size: number; }; type Circle = Extract<Shape, { kind: 'circle' }>;
NonNullable<T> Constructs a type by excluding null and undefined from T. Useful when you know a value cannot be nullish. type MaybeString = string \| null \| undefined; type DefiniteString = NonNullable<MaybeString>; // string
ReturnType<T> Constructs a type consisting of the return type of function T. Useful for typing variables based on function results. declare function f(): { a: number; b: string }; type FuncReturn = ReturnType<typeof f>; // { a: number; b: string }
InstanceType<T> Constructs a type consisting of the instance type of a constructor function type T. Useful for working with class instances. class C { x = 0; } type CInstance = InstanceType<typeof C>; // C
Parameters<T> Constructs a tuple type from the types used in the parameters of a function type T. Useful for manipulating function arguments. declare function greet(name: string, age: number): void; type GreetParams = Parameters<typeof greet>; // [name: string, age: number]
ConstructorParameters<T> Constructs a tuple or array type from the types of a constructor function's parameters. Useful for factory functions. class Person { constructor(name: string, age: number) {} } type PersonArgs = ConstructorParameters<typeof Person>; // [name: string, age: number]
ThisParameterType<T> Extracts the type of the this parameter for a function type, or unknown if the function type has no this parameter. function fn(this: Date, x: number) {} type ThisType = ThisParameterType<typeof fn>; // Date
OmitThisParameter<T> Removes the this parameter from a function type T. Useful for callbacks or detaching methods. function fn(this: Date, x: number): string { return ''; } const fnNoThis: OmitThisParameter<typeof fn> = (x) => ''; // (x: number) => string
ThisType<T> This utility does not return a transformed type. Instead, it serves as a marker for a contextual this type. Use with noImplicitThis. interface HelperThis { log: (msg: string) => void; } function f(this: HelperThis) {} // Advanced use, often in library design.
Awaited<T> Recursively unwraps the Awaited type of a Promise. Useful for getting the resolved value type of nested promises (TS 4.5+). type NestedPromise = Promise<Promise<string>>; type ResolvedValue = Awaited<NestedPromise>; // string

Custom Utility Types (Commonly used custom combinations)

While TypeScript's built-in utilities cover many cases, sometimes you need more specialized type transformations. Here are some commonly implemented custom utility types.

DeepPartial<T>

Recursively makes all properties in an object type optional, including nested objects and arrays. This is useful for scenarios like applying partial updates to deeply nested configuration objects.

TYPESCRIPT

DeepReadonly<T>

Recursively makes all properties in an object type readonly, including nested objects and arrays. This ensures deep immutability, preventing accidental modifications anywhere in the structure.

TYPESCRIPT

Mutable<T>

Removes the readonly modifier from all properties in a type T. This is the inverse of Readonly<T> and can be useful when you need to create a mutable copy of a readonly object.

TYPESCRIPT

Nullable<T>

Constructs a type that allows T or null. Useful for representing values that might be absent or explicitly set to null.

TYPESCRIPT

OptionalKeys<T>

Extracts the keys of T whose properties are optional (can be undefined).

TYPESCRIPT

RequiredKeys<T>

Extracts the keys of T whose properties are required (must be present and cannot be undefined).

TYPESCRIPT

UnionToIntersection<T>

Converts a union type U into an intersection type. This is often used in advanced scenarios involving function overloads or combining multiple type definitions.

TYPESCRIPT

DeepNonNullable<T>

Recursively removes null and undefined from all properties in a type T, including nested objects.

TYPESCRIPT

Summary Table

This table categorizes the utility types based on their primary function:

Category Utility Types
Property Modifiers Partial, Required, Readonly, Mutable, DeepPartial, DeepReadonly
Property Selection Pick, Omit
Union/Intersection Exclude, Extract, UnionToIntersection
Nullability NonNullable, Nullable, DeepNonNullable
Function/Class Introspection ReturnType, Parameters, InstanceType, ConstructorParameters, Awaited
this Parameter ThisParameterType, OmitThisParameter, ThisType
Key Manipulation Record, OptionalKeys, RequiredKeys

Understanding and utilizing these built-in and custom utility types can significantly streamline your TypeScript development, leading to more robust, readable, and maintainable code. Feel free to experiment with them in your projects!

Previous Using Glob Patterns in TypeScript Projects
Next Docker Command Documentation
Random Insta Public Archiver
An unhandled error has occurred. Reload