Jaehyeon
Heo
(Teddy)

Software Engineer

TypeScript Best Practices for 2024

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.

1. Embrace Strict Mode

Always enable strict mode in your tsconfig.json:

{
	"compilerOptions": {
		"strict": true,
		"noUncheckedIndexedAccess": true,
		"exactOptionalPropertyTypes": true
	}
}

2. Use Utility Types Effectively

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;

3. Leverage Template Literal Types

Create powerful string manipulation types:

type EventName<T extends string> = `on${Capitalize<T>}`;
type MouseEvent = EventName<"click">; // 'onClick'

4. Use Branded Types for Domain Modeling

type UserId = string & { __brand: "UserId" };
type Email = string & { __brand: "Email" };
 
function createUser(id: UserId, email: Email) {
	// Implementation
}

5. Implement Proper Error Handling

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 };
	}
}

6. Use Const Assertions

const routes = ["/home", "/about", "/contact"] as const;
 
type Route = (typeof routes)[number]; // '/home' | '/about' | '/contact'

Conclusion

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.