TypeScript Tips and Tricks for Better Code
Published on
by Nguyễn Công Dũngtypescriptjavascripttutorial
TypeScript Tips and Tricks for Better Code
TypeScript has become the de facto standard for building large-scale JavaScript applications. Here are some advanced tips and tricks to help you write better TypeScript code.
Utility Types
TypeScript provides powerful utility types that can save you time:
Partial<T>
Makes all properties optional:
interface User {
name: string;
email: string;
age: number;
}
type PartialUser = Partial<User>;
// { name?: string; email?: string; age?: number; }Pick<T, K>
Select specific properties:
type UserName = Pick<User, 'name' | 'email'>;
// { name: string; email: string; }Omit<T, K>
Exclude specific properties:
type UserWithoutAge = Omit<User, 'age'>;
// { name: string; email: string; }Type Guards
Type guards help TypeScript narrow types:
function isString(value: unknown): value is string {
return typeof value === 'string';
}
function processValue(value: unknown) {
if (isString(value)) {
// TypeScript knows value is string here
console.log(value.toUpperCase());
}
}Discriminated Unions
Use discriminated unions for better type safety:
type Result<T> =
| { success: true; data: T }
| { success: false; error: string };
function handleResult<T>(result: Result<T>) {
if (result.success) {
// TypeScript knows result.data exists
console.log(result.data);
} else {
// TypeScript knows result.error exists
console.error(result.error);
}
}Const Assertions
Use as const to create literal types:
const colors = ['red', 'green', 'blue'] as const;
type Color = typeof colors[number]; // 'red' | 'green' | 'blue'Template Literal Types
Create complex string types:
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<'click'>; // 'onClick'Best Practices
- Use strict mode: Enable all strict checks in
tsconfig.json - Avoid
any: Useunknownwhen type is truly unknown - Leverage type inference: Let TypeScript infer types when possible
- Use interfaces for objects: Prefer interfaces over type aliases for object shapes
- Document complex types: Add JSDoc comments for complex type definitions
Happy typing!