TypeScript has evolved significantly, and with it, the patterns and practices that make our code more robust and maintainable. Here are the essential practices every TypeScript developer should know.
Always enable strict mode in your tsconfig.json:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
}
}TypeScript's built-in utility types can save you time and improve type safety:
// Pick specific properties
type UserBasics = Pick<User, "id" | "name" | "email">;
// Make all properties optional
type PartialUser = Partial<User>;
// Create unions from object keys
type UserKeys = keyof User;Create powerful string manipulation types:
type EventName<T extends string> = `on${Capitalize<T>}`;
type MouseEvent = EventName<"click">; // 'onClick'type UserId = string & { __brand: "UserId" };
type Email = string & { __brand: "Email" };
function createUser(id: UserId, email: Email) {
// Implementation
}type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
async function fetchUser(id: string): Promise<Result<User>> {
try {
const user = await api.getUser(id);
return { success: true, data: user };
} catch (error) {
return { success: false, error: error as Error };
}
}const routes = ["/home", "/about", "/contact"] as const;
type Route = (typeof routes)[number]; // '/home' | '/about' | '/contact'These practices will help you write more maintainable, type-safe TypeScript code. Remember that TypeScript is constantly evolving, so stay updated with the latest features and community best practices.