TypeScript Utility Types
TypeScript utility types are built-in helpers that transform one type into another. Instead of writing the same modified shape by hand, you apply a utility like Partial<User> or Pick<User, "name">. This keeps your code shorter and your types consistent with the source. In real projects, utility types power update payloads, safe dictionaries, and reusable API helpers.
This tutorial uses a single User interface as the base and applies ten utility types to it: Partial, Required, Readonly, Pick, Omit, Record, Exclude, Extract, NonNullable, and ReturnType. Each section shows the exact type that results, so you can see what changes.
What Are TypeScript Utility Types?
TypeScript utility types are generic types that take one or more types and produce a new type. They are available globally without imports. Each one changes the input in a specific way, such as making properties optional, removing some, or extracting a return type.
Here is a quick example:
interface User {
id: number;
name: string;
email: string;
age: number;
}
type UserPreview = Pick<User, "id" | "name">;
const preview: UserPreview = { id: 1, name: "Riya" };
console.log(preview);
// Output: { id: 1, name: 'Riya' }
UserPreview is the same User type but only with id and name. The compiler still checks those two fields against the original types.
How Do Partial, Required, and Readonly Work?
These three change the modifiers on every property. Partial makes all properties optional. Required makes all properties required. Readonly makes all properties readonly. They are the most common utilities in day-to-day code.
interface User {
id: number;
name: string;
email: string;
age: number;
}
type PartialUser = Partial<User>;
// { id?: number; name?: string; email?: string; age?: number }
type RequiredUser = Required<PartialUser>;
// { id: number; name: string; email: string; age: number }
type ReadonlyUser = Readonly<User>;
// { readonly id: number; readonly name: string; ... }
const patch: PartialUser = { name: "Sana" };
const full: RequiredUser = { id: 1, name: "Sana", email: "s@x.com", age: 30 };
const ro: ReadonlyUser = { id: 2, name: "Arjun", email: "a@x.com", age: 28 };
// ro.name = "New";
// Error: Cannot assign to 'name' because it is a read-only property.
console.log(patch, full.id, ro.id);
// Output: { name: 'Sana' } 1 2
How it works: Partial<User> adds ? to every property, so patch can contain only name. Required<PartialUser> removes the ? again, so full must supply all four. Readonly<User> adds readonly to each property, so reassigning ro.name fails. Notice how they compose: utilities accept other utility outputs as input.
How Do Pick and Omit Work?
Pick<T, K> keeps only the listed keys. Omit<T, K> keeps everything except the listed keys. Both are useful for building focused views of a larger type, such as a preview or a create payload that excludes server-generated fields.
interface User {
id: number;
name: string;
email: string;
age: number;
}
type UserPreview = Pick<User, "id" | "name">;
// { id: number; name: string }
type CreateUser = Omit<User, "id">;
// { name: string; email: string; age: number }
const preview: UserPreview = { id: 1, name: "Meera" };
const newUser: CreateUser = { name: "Meera", email: "m@x.com", age: 24 };
console.log(preview, newUser.name);
// Output: { id: 1, name: 'Meera' } Meera
How it works: Pick narrows the type to exactly the chosen keys, so preview cannot include email. Omit removes id, which is the field a server usually generates. The remaining fields must all be present. If you pass an invalid key to Pick, such as "phone", the compiler rejects it because "phone" is not in User.
How Does Record Work for Dictionaries?
Record<K, V> builds an object type whose keys are K and whose values are V. It is the standard way to type dictionaries, lookup tables, and maps from a string ID to a value. K can be a string union, so the keys are checked.
interface User {
id: number;
name: string;
email: string;
age: number;
}
type UsersById = Record<string, User>;
const store: UsersById = {
u1: { id: 1, name: "Riya", email: "r@x.com", age: 28 },
u2: { id: 2, name: "Arjun", email: "a@x.com", age: 32 },
};
console.log(store.u1.name);
// Output: Riya
How it works: Record<string, User> says every string key maps to a User. You can add as many users as you need without changing the type. If you used a literal union like Record<"u1" | "u2", User>, the keys would be fixed, and adding u3 would fail. Choose the key type based on whether the set of keys is fixed or open.
How Do Exclude, Extract, and NonNullable Work?
These three operate on unions. Exclude<T, U> removes members of T that are assignable to U. Extract<T, U> keeps only those members. NonNullable<T> removes null and undefined. They are useful for filtering union types without writing them again by hand.
type Role = "admin" | "editor" | "viewer";
type WriteRole = Exclude<Role, "viewer">;
// "admin" | "editor"
type ReadOnlyRole = Extract<Role, "viewer" | "guest">;
// "viewer"
type MaybeEmail = string | null | undefined;
type Email = NonNullable<MaybeEmail>;
// string
const write: WriteRole = "editor";
const read: ReadOnlyRole = "viewer";
const email: Email = "x@y.com";
console.log(write, read, email);
// Output: editor viewer x@y.com
How it works: Exclude<Role, "viewer"> removes "viewer", leaving the two write-capable roles. Extract<Role, "viewer" | "guest"> keeps only the members that also appear in the second union, which is "viewer" because "guest" is not in Role. NonNullable<MaybeEmail> strips null and undefined, leaving string. These utilities only work meaningfully on unions; on a plain object type, they may produce the whole type or never.
How Does ReturnType Work?
ReturnType<T> extracts the return type of a function type. It is handy when a function's return type is complex and you want to reuse it without copying. Combined with typeof, it can derive types from existing functions.
function createUser(name: string, email: string) {
return { id: 1, name, email, createdAt: new Date() };
}
type NewUser = ReturnType<typeof createUser>;
// { id: number; name: string; email: string; createdAt: Date }
const user: NewUser = {
id: 2,
name: "Vikram",
email: "v@x.com",
createdAt: new Date("2025-01-01"),
};
console.log(user.name);
// Output: Vikram
How it works: typeof createUser gives the function's type. ReturnType reads the return type from that function type. The result is the object shape the function produces, including createdAt: Date. This is useful when a function builds a complex object and you want a type for variables or parameters without duplicating the shape.
Summary Table of Utility Types
| Utility | What It Does | Example Result on User |
|---|---|---|
Partial<T> |
Makes all properties optional | All fields optional |
Required<T> |
Makes all properties required | All fields required |
Readonly<T> |
Makes all properties readonly | All fields readonly |
Pick<T, K> |
Keeps only listed keys | { id, name } |
Omit<T, K> |
Removes listed keys | Everything except id |
Record<K, V> |
Builds a key-value object type | Record<string, User> |
Exclude<T, U> |
Removes union members | Removes "viewer" |
Extract<T, U> |
Keeps matching union members | Keeps "viewer" |
NonNullable<T> |
Removes null and undefined |
string from string | null |
ReturnType<T> |
Gets a function’s return type | The user object shape |
Common Mistakes and Best Practices
- Using
Partialwhere the API actually requires fields. An update payload usually usesPartial, but a create payload should not. Marking everything optional lets callers skip required data, which leads to runtime errors. - Using
Omitwith a key that does not exist. TypeScript reports an error only in some cases, so a typo in the key can go unnoticed. PreferPickwhen you know exactly which keys you want, because unknown keys are rejected more reliably. - Using
Excludeon object types.ExcludeandExtractwork on unions, not object shapes. On an object type, the result may be the same type ornever, which is confusing. Use them for string or number unions. - Forgetting that
Readonlyis shallow.Readonly<User>makes top-level properties readonly, but nested objects can still change. Use a deep readonly helper or readonly arrays if you need full immutability. - Overusing
ReturnTypefor stable APIs. It ties the consumer type to the function's implementation. If the function changes its return shape, every consumer changes too. For public contracts, declare the type explicitly instead.
Real-World Example: Update Payload and Dictionary
This example reuses one User interface to build an update payload with Partial, a create payload with Omit, a dictionary with Record, and a readonly view.
interface User {
id: number;
name: string;
email: string;
age: number;
}
type UserPatch = Partial<Pick<User, "name" | "email" | "age">>;
type NewUser = Omit<User, "id">;
type UserStore = Record<string, Readonly<User>>;
const patch: UserPatch = { email: "new@x.com" };
const newUser: NewUser = { name: "Riya", email: "r@x.com", age: 28 };
const store: UserStore = {
u1: { id: 1, name: "Riya", email: "r@x.com", age: 28 },
u2: { id: 2, name: "Arjun", email: "a@x.com", age: 32 },
};
function applyPatch(user: Readonly<User>, changes: UserPatch): User {
return { ...user, ...changes };
}
const updated = applyPatch(store.u1, patch);
console.log(updated.email);
console.log(newUser.name);
console.log(Object.keys(store).length);
// Output: new@x.com
// Output: Riya
// Output: 2
How it works, line by line. UserPatch combines two utilities: Pick narrows to editable fields, then Partial makes them optional. That is exactly what an update endpoint needs. NewUser uses Omit to drop id, which the server assigns. UserStore uses Record<string, Readonly<User>> so every user is stored under a string key and cannot be mutated in place. The applyPatch function accepts a readonly user and a patch, then spreads both into a new object, returning a normal User. updated.email picks up the patch value, newUser.name comes from the create payload, and Object.keys(store).length confirms two entries. Notice that every type is derived from the single User interface, so a change to User flows through all of them. The TypeScript Generics tutorial explains the machinery behind these utilities if you want to see how they are defined.
Summary
- TypeScript utility types transform one type into another and are built into the language.
Partial,Required, andReadonlychange property modifiers across the whole type.PickandOmitbuild focused views by selecting or removing keys.Recordtypes dictionaries from a key type to a value type, with checked keys.Exclude,Extract, andNonNullablefilter unions;ReturnTypereads a function's output type.- Real uses include update payloads with
Partial, create payloads withOmit, and dictionaries withRecord.
Now that you can reshape types with utilities, continue to the Type Guards & Narrowing tutorial to learn how to tell TypeScript exactly which type you have at runtime.
Frequently Asked Questions
Are utility types available without importing anything?
Yes. All built-in utility types like Partial, Pick, and Record are part of the global TypeScript type system. You do not import them. Just write Partial<User> and the compiler understands it. Custom utility types would need to be defined or imported from a library.
What is the difference between Pick and Omit?
Pick<T, K> keeps only the keys you list, so the result has fewer properties. Omit<T, K> removes the keys you list and keeps everything else. Use Pick when you know exactly which fields you want, and Omit when you want almost everything except a few fields.
Does Readonly make nested objects immutable too?
No. Readonly<T> is shallow; it marks only the top-level properties as readonly. A nested object or array inside can still be mutated. For deep immutability, you need a recursive mapped type or a library helper. Use readonly arrays and explicit deep-readonly helpers when full immutability matters.
Can I combine two utility types in one annotation?
Yes. Utilities compose naturally. For example, Partial<Pick<User, "name" | "email">> first narrows to those two keys and then makes them optional. This is common for update payloads. You can nest as many as you need, but keep the expression readable by naming it with a type alias.
Why does Exclude return never on my object type?
Exclude and Extract work on union types, not object shapes. If you pass an object type, it is treated as a single member, so excluding a string literal removes nothing or removes everything depending on assignability. Use these utilities only with unions of primitives or literal types.
Practice Exercises
Exercise 1 (Easy): Create a Partial Update Payload
Using a User interface with id, name, and email, create a type UserPatch = Partial<User> and one object with only email.
Show solution
interface User {
id: number;
name: string;
email: string;
}
type UserPatch = Partial<User>;
const patch: UserPatch = { email: "new@x.com" };
console.log(patch);
// Output: { email: 'new@x.com' }
Partial<User> makes every property optional, so a patch with only email is valid.
Exercise 2 (Easy): Use Pick and Omit
Create Preview = Pick<User, "id" | "name"> and CreateUser = Omit<User, "id">. Build one object of each.
Show solution
interface User {
id: number;
name: string;
email: string;
}
type Preview = Pick<User, "id" | "name">;
type CreateUser = Omit<User, "id">;
const p: Preview = { id: 1, name: "Riya" };
const c: CreateUser = { name: "Arjun", email: "a@x.com" };
console.log(p, c.name);
// Output: { id: 1, name: 'Riya' } Arjun
Pick keeps only the chosen keys, while Omit removes id and keeps the rest.
Exercise 3 (Medium): Record Dictionary and NonNullable
Create Store = Record<string, User> with two entries. Then take a string | null value and use NonNullable to get a string variable.
Show solution
interface User {
id: number;
name: string;
}
type Store = Record<string, User>;
const store: Store = {
u1: { id: 1, name: "Riya" },
u2: { id: 2, name: "Arjun" },
};
type MaybeName = string | null;
const raw: MaybeName = "Riya";
const name: NonNullable<MaybeName> = raw!;
console.log(Object.keys(store).length, name);
// Output: 2 Riya
Record types the dictionary with string keys, and NonNullable removes null so the variable is just a string.
Exercise 4 (Challenge): ReturnType and Readonly
Write a function makeUser that returns an object with id, name, and createdAt. Derive NewUser = ReturnType<typeof makeUser> and create a Readonly<NewUser> variable. Show that reassigning a field fails.
Show solution
function makeUser(name: string) {
return { id: 1, name, createdAt: new Date("2025-01-01") };
}
type NewUser = ReturnType<typeof makeUser>;
const u: Readonly<NewUser> = { id: 2, name: "Sana", createdAt: new Date("2025-02-01") };
// u.name = "Other";
// Error: Cannot assign to 'name' because it is a read-only property.
console.log(u.name, u.createdAt.getFullYear());
// Output: Sana 2025
ReturnType captures the object shape from the function, and Readonly blocks reassignment of any top-level field.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
