Menu

Type-Safety Best Practices and Anti-Patterns

Lesson 3: Type-Safety Best Practices and Anti-Patterns

What do good TypeScript codebases do?

Practice Why
Keep strict on, plus noUncheckedIndexedAccess Catches the most bugs
Prefer unknown to any Forces checks instead of hiding problems
Validate data at boundaries, trust types inside One place for runtime checks
Model states with discriminated unions Invalid states cannot be represented
Derive types (typeof, utility types, z.infer) One source of truth
Let TypeScript infer locals; annotate exported APIs Clear contracts, less noise
Keep types close to where they are used Easier to find and change

Anti-patterns and fixes

Anti-pattern Example Problem Better
any everywhere function save(data: any) No checking Specific type or unknown
Unsafe assertion const p = data as Product Trusts unchecked data Validate or narrow
Non-null assertion user!.address!.city Crashes when missing Optional chaining and checks
Optional everything { id?: string; name?: string } Every use needs checks Make only real optional fields optional
Boolean flags for state isLoading, isError, isSuccess Contradictory combinations Discriminated union status
Over-engineered types Five nested conditional types for a form Unreadable errors Simple explicit types
@ts-ignore comments Silences any error Hides future errors too Fix it, or @ts-expect-error with a reason

Example

// Before: flags can contradict each other
type CheckoutStateBad = {
  isLoading: boolean;
  isError: boolean;
  orderId?: string;
  error?: string;
};

// After: each state carries exactly what it needs
type CheckoutState =
  | { status: 'idle' }
  | { status: 'submitting' }
  | { status: 'success'; orderId: string }
  | { status: 'error'; error: string };

// Before
const city = order.customer!.address!.city;

// After
const city = order.customer?.address?.city ?? 'Unknown';

How it works

  • Most production TypeScript bugs come from the escape hatches: any, as, and !. Search for them in code review.
  • Simple, explicit types usually beat clever ones. Reserve advanced types for shared utilities.
  • Name types after what they represent (OrderStatus), not their shape (StringUnion1).

Common mistakes

Mistake Effect Fix
Treating type errors as obstacles Casts and ignores pile up Treat them as bug reports
Copying types between front end and back end They drift apart Share a package or generate types from a schema
Large types.ts file for the whole app Hard to navigate Keep types beside the code that owns them

Key takeaways

  • Avoid any, as, !, and @ts-ignore unless you have a written reason.
  • Model data precisely and derive types from a single source.

Try it: Search a TypeScript project for any, as, and !.. Replace three of them with safer code.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details