Cheatsheet TypeScript: Utility Types que Você Precisa Conhecer
Guia de referência rápida para os utility types mais poderosos do TypeScript, com exemplos práticos de uso no dia a dia.
Partial<T>
Torna todas as propriedades opcionais. Perfeito para updates parciais:
interface User {
name: string;
email: string;
age: number;
}
function updateUser(id: string, data: Partial<User>) {
// data pode ter qualquer combinação de name, email, age
}
updateUser('1', { name: 'Ivan' }); // OK
updateUser('1', { email: 'ivan@dev.com', age: 25 }); // OK
Pick<T, K> e Omit<T, K>
Selecionar ou excluir propriedades:
type UserPreview = Pick<User, 'name' | 'email'>;
// { name: string; email: string }
type UserWithoutAge = Omit<User, 'age'>;
// { name: string; email: string }
Record<K, V>
Mapear chaves para valores:
type Role = 'admin' | 'editor' | 'viewer';
type Permissions = Record<Role, string[]>;
const perms: Permissions = {
admin: ['read', 'write', 'delete'],
editor: ['read', 'write'],
viewer: ['read'],
};
Required<T>
Oposto do Partial — torna tudo obrigatório:
interface Config {
host?: string;
port?: number;
ssl?: boolean;
}
type RequiredConfig = Required<Config>;
// { host: string; port: number; ssl: boolean }
Extract<T, U> e Exclude<T, U>
Filtrar tipos de union:
type Event = 'click' | 'scroll' | 'mousemove' | 'keydown';
type MouseEvent = Extract<Event, 'click' | 'mousemove'>;
// 'click' | 'mousemove'
type NonMouseEvent = Exclude<Event, 'click' | 'mousemove'>;
// 'scroll' | 'keydown'
ReturnType<T> e Parameters<T>
Inferir tipos de funções:
function createUser(name: string, age: number) {
return { id: crypto.randomUUID(), name, age, createdAt: new Date() };
}
type UserReturn = ReturnType<typeof createUser>;
// { id: string; name: string; age: number; createdAt: Date }
type UserParams = Parameters<typeof createUser>;
// [name: string, age: number]
NonNullable<T>
Remover null e undefined:
type MaybeString = string | null | undefined;
type DefinitelyString = NonNullable<MaybeString>;
// string
Template Literal Types
type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type APIRoute = '/users' | '/posts';
type Endpoint = `${HTTPMethod} ${APIRoute}`;
// 'GET /users' | 'GET /posts' | 'POST /users' | ...



