Practical TypeScript patterns that improve code quality, readability, and maintainability.
TypeScript has become the default for serious frontend and full-stack development. Writing it well matters more than ever.
unknown Over anyany disables type checking. Prefer unknown and narrow the type:
function processData(data: unknown) {
if (typeof data === 'string') {
return data.toUpperCase();
}
if (Array.isArray(data)) {
return data.length;
}
throw new Error('Unsupported data type');
}
Instead of optional fields or complex conditionals, use a discriminant:
type Result =
| { status: 'success'; data: string }
| { status: 'error'; message: string };
function handleResult(result: Result) {
if (result.status === 'success') {
console.log(result.data);
} else {
console.error(result.message);
}
}
const Assertions and as constconst routes = ['/', '/about', '/blog'] as const;
type Route = (typeof routes)[number]; // '/' | '/about' | '/blog'
Type assertions (as) should be a last resort. Prefer proper type guards or better modeling.
| Utility | Purpose |
|---|---|
Partial<T> | Makes all properties optional |
Required<T> | Makes all properties required |
Pick<T, K> | Selects specific keys |
Omit<T, K> | Removes specific keys |
Record<K, V> | Creates a map type |
strict mode in tsconfig.jsonClean TypeScript is less about fancy features and more about clear, honest modeling of your data.