TypeScript Utility Types


TypeScript provides several utility types to help developers work with types more effectively. These utility types can manipulate existing types, extract parts of types, or create new types based on existing ones. They enhance code readability, maintainability, and type safety.

Let’s explore a few commonly used utility types:

interface User {
  name: string;
  age: number;
  email?: string;
}

const partialUser: Partial<User> = { name: 'John' }; // No error, age and email are optional
interface User {
  name: string;
  age: number;
  email?: string;
}

const requiredUser: Required<User> = { name: 'John', age: 30, email: 'john@example.com' }; // email is now required
interface User {
  name: string;
  age: number;
}

const readonlyUser: Readonly<User> = { name: 'John', age: 30 };
readonlyUser.age = 31; // Error: Cannot assign to 'age' because it is a read-only property.
type Weekdays = 'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday';
const workSchedule: Record<Weekdays, number> = {
  Monday: 8,
  Tuesday: 9,
  Wednesday: 8,
  Thursday: 7,
  Friday: 6,
};
interface User {
  name: string;
  age: number;
  email: string;
}

const userNameAndEmail: Pick<User, 'name' | 'email'> = { name: 'John', email: 'john@example.com' };
interface User {
  name: string;
  age: number;
  email: string;
}

const userWithoutEmail: Omit<User, 'email'> = { name: 'John', age: 30 };

These are just a few examples of the many utility types available in TypeScript. Leveraging these built-in utilities can significantly improve your type management and overall code quality. Refer to the official TypeScript documentation for a comprehensive list and more detailed explanations.