Back to Blog

10 TypeScript Tips for Writing Better Code

Discover essential TypeScript tips and tricks that will help you write cleaner, safer, and more maintainable code in your projects.

10 TypeScript Tips for Writing Better Code

TypeScript has become the standard for modern web development. Here are 10 tips that will help you write better TypeScript code.

1. Use Strict Mode

Always enable strict mode in your tsconfig.json:

json
{
  "compilerOptions": {
    "strict": true
  }
}

2. Leverage Type Inference

Don't over-annotate. TypeScript can infer types:

typescript
// Unnecessary
const name: string = "John";

// Better - TypeScript infers the type const name = "John";

3. Use Union Types

Union types make your code more flexible:

typescript
type Status = "pending" | "approved" | "rejected";

function updateStatus(status: Status) { // TypeScript ensures only valid values are passed }

4. Utilize Utility Types

TypeScript provides powerful utility types:

typescript
interface User {
  id: number;
  name: string;
  email: string;
}

// Make all properties optional
type PartialUser = Partial<User>;

// Make all properties required
type RequiredUser = Required<User>;

// Pick specific properties type UserPreview = Pick<User, "id" | "name">;

5. Use const assertions

Const assertions create more specific types:

typescript
const config = {
  endpoint: "/api",
  timeout: 5000,
} as const;
// config.endpoint is now "/api" not string

6. Generic Functions

Generics make your functions reusable:

typescript
function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

const num = first([1, 2, 3]); // number const str = first(["a", "b"]); // string

7. Type Guards

Type guards narrow types safely:

typescript
function isString(value: unknown): value is string {
  return typeof value === "string";
}

function process(value: unknown) { if (isString(value)) { console.log(value.toUpperCase()); // TypeScript knows it's a string } }

8. Use satisfies Operator

The satisfies operator validates types while preserving inference:

typescript
const palette = {
  red: [255, 0, 0],
  green: "#00ff00",
} satisfies Record<string, string | number[]>;

9. Discriminated Unions

Create type-safe state machines:

typescript
type State =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: string }
  | { status: "error"; error: Error };

10. Template Literal Types

Create complex string types:

typescript
type EventName = on${Capitalize<string>};
// Matches "onClick", "onHover", etc.

Conclusion

These TypeScript tips will help you write more robust and maintainable code. Remember, TypeScript is a tool to help you - use it wisely to catch bugs at compile time rather than runtime.

Happy coding!