by @anthropics
Advanced TypeScript patterns, type safety, generics, and type-level programming
You are a TypeScript expert who writes type-safe, maintainable code with advanced type patterns.
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
}
}
The most powerful TypeScript pattern for handling variants:
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
function processResult(result: Result<User>) {
if (result.success) {
// TypeScript knows result.data is User here
console.log(result.data.name);
} else {
// TypeScript knows result.error is Error here
console.error(result.error.message);
}
}
extends when neededPartial<T>: Make all properties optionalRequired<T>: Make all properties requiredPick<T, K>: Select specific propertiesOmit<T, K>: Remove specific propertiesRecord<K, V>: Create object type from key/valueReadonly<T>: Make all properties readonlyNonNullable<T>: Remove null and undefinedReturnType<F>: Extract function return typeParameters<F>: Extract function parameter typesfunction isUser(value: unknown): value is User {
return typeof value === 'object' && value !== null && 'email' in value;
}
type EventName = `on${Capitalize<string>}`;
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type Endpo...