TypeScript’s utility types give you powerful ways to transform and manipulate existing types. If you’ve already used types like Partial
or Pick
, it’s time to expand your toolbox.
In this article, we'll focus on five highly useful utility types:
Omit<Type, Keys>
Exclude<UnionType, ExcludedMembers>
Extract<UnionType, IncludedMembers>
NonNullable<Type>
Parameters<Type>
1. Omit<Type, Keys>
Omit
creates a new type by removing specified keys from another type.
Example
interface User {
id: number;
name: string;
email: string;
}
type UserWithoutEmail = Omit<User, 'email'>;
// Result:
type UserWithoutEmail = {
id: number;
name: string;
}
Use Case
Perfect when you need to reuse most of a type but exclude a few fields—for example, when hiding sensitive information.
2. Exclude<UnionType, ExcludedMembers>
Exclude
removes members of a union that are assignable to another type.
Example
type Roles = 'admin' | 'user' | 'guest';
type NonGuest = Exclude<Roles, 'guest'>;
// Result: 'admin' | 'user'
Use Case
Useful when you want to filter out specific options from a union.
3. Extract<UnionType, IncludedMembers>
Extract
is the opposite of Exclude
. It keeps only the members that are assignable to another type.
Example
type Events = 'click' | 'hover' | 'scroll';
type UIEvents = Extract<Events, 'click' | 'hover'>;
// Result: 'click' | 'hover'
Use Case
Helpful when you want to narrow a union type to only valid choices.
4. NonNullable<Type>
NonNullable
removes null
and undefined
from a type.
Example
type MaybeUser = User | null | undefined;
type DefinedUser = NonNullable<MaybeUser>;
// Result: User
Use Case
Great when you want to ensure a type is fully usable, for example, after a null-check.
5. Parameters<Type>
Parameters
extracts the tuple of parameter types from a function type.
Example
function createUser(id: number, name: string): User {
return { id, name };
}
type Args = Parameters<typeof createUser>;
// Result: [id: number, name: string]
Use Case
Useful for reusing or forwarding function arguments dynamically.
Summary Table
Utility Type | What It Does |
Omit<T, K> | Removes keys K from type T |
Exclude<T, U> | Removes members of union T that are assignable to U |
Extract<T, U> | Keeps only members of union T that are assignable to U |
NonNullable<T> | Removes null and undefined from type T |
Parameters<T> | Extracts argument types of function T as a tuple |
Wrapping Up
These utility types are essential when writing scalable TypeScript code. They allow you to:
- Create flexible APIs
- Simplify code reuse
- Ensure type safety in transformations
By mastering them, you'll write more expressive and maintainable code.