
Ts Utility Types in TypeScript
TypeScript provides a set of built-in utility types that make it easier to manipulate and transform existing types. These utility types are designed to simplify common type transformations, enhancing code reusability and type safety.
Common Utility Types
Partial
Required
Readonly
Pick
Omit
Record
Exclude
Extract
NonNullable
ReturnType
InstanceType
Parameters
ConstructorParameters
Detailed Explanation and Examples
1. Partial<T>
Makes all properties of type T
optional.
interface User { id: number; name: string; email: string;}let partialUser: Partial<User> = { name: "Alice" };
2. Required<T>
Makes all properties of type T
required.
interface User { id?: number; name?: string;}let user: Required<User> = { id: 1, name: "Alice" }; // Error if any property is missing
3. Readonly<T>
Makes all properties of type T
readonly.
interface User { id: number; name: string;}const readonlyUser: Readonly<User> = { id: 1, name: "Alice" };// readonlyUser.id = 2; // Error: Cannot assign to 'id' because it is a read-only property
4. Pick<T, K>
Creates a type by picking specific properties K
from type T
.
interface User { id: number; name: string; email: string;}type UserInfo = Pick<User, "id" | "name">;let userInfo: UserInfo = { id: 1, name: "Alice" };
5. Omit<T, K>
Creates a type by omitting specific properties K
from type T
.
interface User { id: number; name: string; email: string;}type UserWithoutEmail = Omit<User, "email">;let user: UserWithoutEmail = { id: 1, name: "Alice" };
6. Record<K, T>
Creates a type with property keys of type K
and values of type T
.
type Role = "admin" | "user" | "guest";let userRoles: Record<Role, string> = { admin: "Alice", user: "Bob", guest: "Charlie",};
7. Exclude<T, U>
Excludes from T
those types that are assignable to U
.
type T = string | number | boolean;type Extracted = Extract<T, number | boolean>; // number | boolean
9. NonNullable<T>
Removes null
and undefined
from type T
.
type T = string | null | undefined;type NonNull = NonNullable<T>; // string
10. ReturnType<T>
Extracts the return type of a function type T
.
function getUser() { return { id: 1, name: "Alice" };}type UserType = ReturnType<typeof getUser>; // { id: number; name: string }
11. InstanceType<T>
Extracts the instance type of a class or constructor type T
.
class User { id = 1; name = "Alice";}type UserInstance = InstanceType<typeof User>; // User
12. Parameters<T>
Extracts the types of the parameters of a function type T
.
function login(username: string, password: string): class User { constructor(public id: number, public name: string) {}}type UserConstructorParams = ConstructorParameters<typeof User>; // [number, string]
Use Cases of Utility Types
API Responses
UsePartial
orPick
for handling optional or specific fields in API responses.Immutable Data
UseReadonly
to enforce immutability in configurations or state objects.Type-safe Mappings
UseRecord
for defining structured key-value mappings.Type-safe Filtering
UseExclude
andExtract
for filtering specific types.Dynamic Function Types
UseReturnType
,Parameters
, andConstructorParameters
for dynamic type extraction.
Best Practices
Combine Utility Types
Combine utility types for more advanced use cases.type ImmutableUser = Readonly<Partial<User>>;
Leverage
Pick
andOmit
UsePick
andOmit
to create lean and specific types for APIs or components.Avoid Overusing
any
Use utility types to create flexible yet type-safe structures instead of resorting toany
.Keep Code Readable
Use type aliases when utility types become too complex.
Conclusion
Utility types in TypeScript streamline the process of type manipulation and enable developers to write cleaner, safer, and more reusable code. By understanding these types, you can handle complex type scenarios effectively and improve your codebase's maintainability.