TypeScript's built-in utility types eliminate boilerplate and make your types more expressive. Here are the ones you'll use daily.
Sign in to leave a comment.
No comments yet. Be the first to comment.
TypeScript's built-in utility types eliminate boilerplate and make your types more expressive. Here are the ones you'll use daily.
interface User {
id: string;
name: string;
email: string;
avatar: string;
}
// For update operations — all fields optional
function updateUser(id: string, updates: Partial<User>) {
return db.update("users", id, updates);
}
updateUser("123", { name: "New Name" }); // OK, only nameinterface Config {
host?: string;
port?: number;
ssl?: boolean;
}
// After merging with defaults, all properties exist
const config: Required<Config> = {
host: "localhost",
port: 3000,
ssl: false
};// API response: only public fields
type PublicUser = Pick<User, "id" | "name" | "avatar">;
// Form data: everything except id
type UserForm = Omit<User, "id">;type StatusMap = Record<"pending" | "active" | "disabled", User[]>;
const usersByStatus: StatusMap = {
pending: [],
active: [user1, user2],
disabled: [user3]
};type Event = "click" | "scroll" | "keydown" | "keyup";
type KeyEvent = Extract<Event, "keydown" | "keyup">; // "keydown" | "keyup"
type NonKeyEvent = Exclude<Event, "keydown" | "keyup">; // "click" | "scroll"function createUser(name: string, age: number) {
return { id: crypto.randomUUID(), name, age };
}
type NewUser = ReturnType<typeof createUser>; // { id: string; name: string; age: number }
type CreateUserArgs = Parameters<typeof createUser>; // [string, number]type DeepPartial<T> = {
[K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
};type DeepReadonly<T> = {
readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};type MaybeString = string | null | undefined;
type DefiniteString = NonNullable<MaybeString>; // stringinterface Article {
id: string;
title: string;
content: string;
author: User;
createdAt: Date;
}
type CreateArticleDTO = Omit<Article, "id" | "createdAt" | "author">;
type UpdateArticleDTO = Partial<CreateArticleDTO>;
type ArticlePreview = Pick<Article, "id" | "title"> & { authorName: string };