Object Transformation Types
Object Transformation Types
Partial and Required
interface User {
id: number;
name: string;
email: string;
bio: string;
}
// Partial - all properties optional (great for update functions)
function updateUser(id: number, updates: Partial<User>): void {
// Only the provided properties need to be set
}
updateUser(1, { name: 'New Name' }); // OK
updateUser(1, {}); // OK - no changes
// Required - all properties required (reverses optional)
interface Config {
host?: string;
port?: number;
debug?: boolean;
}
type StrictConfig = Required<Config>;
// { host: string; port: number; debug: boolean }
Readonly
type ReadonlyUser = Readonly<User>;
// All properties become readonly
const user: ReadonlyUser = { id: 1, name: 'Alice', email: 'a@b.com', bio: '' };
// user.name = 'Bob'; // Error: cannot assign to readonly property
// Deep readonly
type DeepReadonly<T> = {
readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};
Selection Types
Selection Types
Pick and Omit
interface User {
id: number;
name: string;
email: string;
password: string;
createdAt: Date;
}
// Pick - select specific properties
type UserPreview = Pick<User, 'id' | 'name' | 'email'>;
// { id: number; name: string; email: string }
// Omit - exclude specific properties
type CreateUserDTO = Omit<User, 'id' | 'createdAt'>;
// { name: string; email: string; password: string }
// Great for API responses
type PublicUser = Omit<User, 'password'>;
Record
// Record<Keys, Type> creates an object type with specific keys and values
const roles: Record<string, string[]> = {
admin: ['read', 'write', 'delete'],
user: ['read'],
guest: []
};
// With enum keys
enum Status {
Active = 'active',
Inactive = 'inactive'
}
const statusLabels: Record<Status, string> = {
[Status.Active]: 'Active User',
[Status.Inactive]: 'Inactive User'
};
// Record with union values
type Permissions = Record<string, ('read' | 'write' | 'execute')[]>;
Function Types
Function Types
ReturnType and Parameters
function createUser(name: string, age: number) {
return { id: Date.now(), name, age, createdAt: new Date() };
}
// Extract return type
type User = ReturnType<typeof createUser>;
// { id: number; name: string; age: number; createdAt: Date }
// Extract parameter types
type CreateUserParams = Parameters<typeof createUser>;
// [string, number]
// Extract specific parameter
type NameParam = Parameters<typeof createUser>[0]; // string
// Awaited - unwrap Promise type
async function fetchUser(id: number): Promise<User> {
const response = await fetch(`/api/users/${id}`);
return response.json();
}
type FetchedUser = Awaited<ReturnType<typeof fetchUser>>;
// User
ConstructorParameters
class Database {
constructor(
private host: string,
private port: number,
private options?: { ssl: boolean }
) {}
}
type DBConfig = ConstructorParameters<typeof Database>;
// [string, number, { ssl: boolean }?]
String and Union Utilities
String and Union Utility Types
Extract and Exclude
type Status = 'pending' | 'active' | 'completed' | 'archived';
// Extract - keep union members that match
type ActiveStatus = Extract<Status, 'active' | 'completed'>;
// 'active' | 'completed'
// Exclude - remove union members that match
type InactiveStatus = Exclude<Status, 'active' | 'completed'>;
// 'pending' | 'archived'
// NonNullable - remove null and undefined
type MaybeString = string | null | undefined;
type DefiniteString = NonNullable<MaybeString>;
// string
String Manipulation
type UpperCase = Uppercase<'hello'>; // 'HELLO'
type LowerCase = Lowercase<'HELLO'>; // 'hello'
type Capitalized = Capitalize<'hello'>; // 'Hello'
type Uncapitalized = Uncapitalize<'Hello'>; // 'hello'
// Template literal types
type EventName = `${'click' | 'hover' | 'focus'}_${'start' | 'end'}`;
// 'click_start' | 'click_end' | 'hover_start' | 'hover_end' | 'focus_start' | 'focus_end'
InstanceType
class Logger {
private logs: string[] = [];
log(message: string): void {
this.logs.push(message);
}
}
type LogInstance = InstanceType<typeof Logger>;
// Logger