JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
PrevNext
typescript
mid
utility-types

What are TypeScript's built-in utility types and when do you use them?

utility-types
partial
pick
omit
record
mapped-types
Quick Answer

Utility types are built-in generic types that transform other types. Common ones include Partial<T> (all optional), Required<T> (all required), Pick<T,K> (select properties), Omit<T,K> (exclude properties), and Record<K,V> (object type).

Detailed Explanation

Property Modifiers:

  • Partial<T>: All properties optional
  • Required<T>: All properties required
  • Readonly<T>: All properties readonly

Property Selection:

  • Pick<T, K>: Select specific properties
  • Omit<T, K>: Exclude specific properties

Type Construction:

  • Record<K, V>: Object with keys K and values V
  • Extract<T, U>: Extract types assignable to U
  • Exclude<T, U>: Remove types assignable to U

Null Handling:

  • NonNullable<T>: Remove null/undefined
  • ReturnType<T>: Get function return type
  • Parameters<T>: Get function parameter types

Code Examples

Partial, Required, Readonly
interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

// Partial - all properties optional (for updates)
type UserUpdate = Partial<User>;
// { id?: number; name?: string; email?: string; age?: number }

function updateUser(id: number, updates: Partial<User>) {
  // Can pass any subset of properties
}
updateUser(1, { name: 'New Name' }); // OK
updateUser(1, { email: 'new@email.com', age: 30 }); // OK

// Required - all properties required (reverse of Partial)
interface Config {
  host?: string;
  port?: number;
}
type FullConfig = Required<Config>;
// { host: string; port: number } - both required now

// Readonly - prevent modifications
type ImmutableUser = Readonly<User>;

const user: ImmutableUser = { id: 1, name: 'Alice', email: 'a@b.c', age: 25 };
user.name = 'Bob'; // Error: Cannot assign to 'name' because it is read-only

Resources

TypeScript - Utility Types

docs

Related Questions

What are generics in TypeScript and how do you use them?

mid
generics

How do mapped types work in TypeScript?

senior
mapped-types
Previous
What are type guards in TypeScript and how do you create custom ones?
Next
How do TypeScript modules work and what's the difference between import types?