Utility Types
TypeScript includes several utility types that help you transform and manipulate existing types. These built-in tools make type operations easier and more consistent.
Partial<T>
Makes all properties optional:
interface User {
id: number;
name: string;
email: string;
}
// All fields are optional
type PartialUser = Partial<User>;
// Valid
const updateUser: PartialUser = {
name: "John" // email and id can be omitted
};
Pick<T, K> and Omit<T, K>
Select or remove specific properties:
interface Article {
title: string;
content: string;
tags: string[];
publishDate: Date;
}
// Only these properties
type ArticlePreview = Pick<Article, 'title' | 'tags'>;
// Everything except these
type DraftArticle = Omit<Article, 'publishDate'>;
Record<K, T>
Creates a type with specified keys and value types:
type UserRoles = Record<string, string[]>;
const roles: UserRoles = {
admin: ['read', 'write', 'delete'],
user: ['read'],
editor: ['read', 'write']
};
Required<T> and Readonly<T>
Make properties required or read-only:
interface Config {
cache?: boolean;
timeout?: number;
retries?: number;
}
// All properties required
type RequiredConfig = Required<Config>;
// All properties read-only
type ReadonlyConfig = Readonly<Config>;
const config: ReadonlyConfig = {
cache: true,
timeout: 1000
};
// config.cache = false; // Error: cannot modify readonly property
Extract<T, U> and Exclude<T, U>
Work with union types:
type Status = 'pending' | 'active' | 'closed' | 'deleted';
// Only these values
type ActiveStatus = Extract<Status, 'pending' | 'active'>;
// Result: 'pending' | 'active'
// Everything except these
type NonDeletedStatus = Exclude<Status, 'deleted'>;
// Result: 'pending' | 'active' | 'closed'
ReturnType<T>
Gets the return type of a function:
function createUser(name: string, age: number) {
return { id: Date.now(), name, age };
}
type User = ReturnType<typeof createUser>;
// Result: { id: number, name: string, age: number }
Best Practices
- Use utility types to avoid repeating type definitions
- Combine utility types for complex transformations
- Consider creating custom utility types for project-specific needs
- Document complex type transformations
Practice Exercise
Create a type system for a task management application using utility types:
- Define a base
Taskinterface - Create types for task creation (omitting ID and dates)
- Create types for task updates (all fields optional)
- Create a read-only type for completed tasks