Back to posts

TypeScript Tips and Tricks for Better Code

Published on
by Nguyễn Công Dũng
typescriptjavascripttutorial

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:

TypeScript
interface User {
  name: string;
  email: string;
  age: number;
}
 
type PartialUser = Partial<User>;
// { name?: string; email?: string; age?: number; }

Pick<T, K>

Select specific properties:

TypeScript
type UserName = Pick<User, 'name' | 'email'>;
// { name: string; email: string; }

Omit<T, K>

Exclude specific properties:

TypeScript
type UserWithoutAge = Omit<User, 'age'>;
// { name: string; email: string; }

Type Guards

Type guards help TypeScript narrow types:

TypeScript
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:

TypeScript
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:

TypeScript
const colors = ['red', 'green', 'blue'] as const;
type Color = typeof colors[number]; // 'red' | 'green' | 'blue'

Template Literal Types

Create complex string types:

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

Best Practices

  1. Use strict mode: Enable all strict checks in tsconfig.json
  2. Avoid any: Use unknown when type is truly unknown
  3. Leverage type inference: Let TypeScript infer types when possible
  4. Use interfaces for objects: Prefer interfaces over type aliases for object shapes
  5. Document complex types: Add JSDoc comments for complex type definitions

Happy typing!