Mastering TypeScript: Tips and Tricks

Le Do NghiemSoftware Engineer
2025-09-10 2 min read

TypeScript is a powerful tool for building robust and scalable JavaScript applications. In this post, I'll share some advanced tips and tricks to help you write cleaner and more maintainable TypeScript code.
Union types allow you to define variables that can hold multiple types, making your code more flexible without sacrificing type safety.
type UserRole = 'admin' | 'editor' | 'viewer';
interface User {
id: number;
name: string;
role: UserRole;
}
function restrictAccess(user: User) {
if (user.role === 'admin' || user.role === 'editor') {
return 'Access granted';
}
return 'Access denied';
}
const user: User = { id: 1, name: 'Alice', role: 'admin' };
console.log(restrictAccess(user)); // Output: Access granted
TypeScript’s utility types, like Partial, Pick, and Omit, can simplify complex type definitions.
interface User {
id: number;
name: string;
email: string;
}
// Create a partial user for updates
type UserUpdate = Partial<User>;
const update: UserUpdate = { name: 'Bob' }; // Only update name
By mastering union types, utility types, and other TypeScript features, you can write more expressive and maintainable code. Stay tuned for more advanced TypeScript tips!