Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 96 ยท TypeScript in Practice

Best Practices and Common Mistakes

Write TypeScript that stays safe as it grows - strict settings, unknown at boundaries, inference, unions, readonly data, fewer assertions, and the six most common errors.

By now you know most of the language. This lesson is about judgment: which features to reach for, which to avoid, and which habits keep a codebase safe after a year of changes by many people. Each practice below comes with the bug it prevents, because a rule you understand is a rule you'll keep.

The second half of the lesson is a field guide to the six error messages you'll see most often (TS2322, TS2345, TS2339, TS7006, TS18048 and TS2532), what each one really means, and the right fix, which is rarely "add as any".

1. Turn strictness on and keep it on

Every lesson in this course uses strict: true, and so should every new project. The strict family (Strict Mode Explained) catches null and undefined mistakes, implicit any and unsafe callbacks. Two extra flags are worth adding on top:

JSON
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitOverride": true,
    "noFallthroughCasesInSwitch": true
  }
}

noUncheckedIndexedAccess makes array[i] and record[key] include undefined, which is the truth at runtime. In an existing project, turn flags on one at a time and fix the errors in batches, as described in Migrating JavaScript to TypeScript. Never turn a flag off to make an error disappear: the error was pointing at a real gap.

2. Use unknown at the boundaries, never any

Data that comes from outside your program (JSON, process.env, files, user input, catch blocks) has no trustworthy type. any pretends it has every type, so mistakes spread silently. unknown admits you don't know yet, and forces a check before use:

TypeScript unknown forces a check, any does not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The any version prints any version: 162 because '16' + 2 is string concatenation. The unknown version can't even touch parsed.fontSize until isSettings has checked it, so it rejects the bad data instead. Validate once at the edge (see Custom Type Guards and Typing APIs and JSON Data) and the rest of your program can trust its types.

JSON.parse returns any for historical reasons. Annotating the result as unknown, as above, is a one-word habit that closes the biggest hole in most codebases.

3. Let inference work, annotate the boundaries

Annotating everything adds noise and can make types worse (an annotation like const mode: string = 'dark' throws away the literal type). Annotating nothing makes errors appear far from their cause. The balance most teams settle on, building on Type Inference:

  • Annotate function parameters (required anyway in strict mode), return types of exported functions, and empty collections (const ids: number[] = []).
  • Infer local variables, callback parameters and anything initialized with a clear value.

An explicit return type is a contract. Without it, a typo in one branch silently changes what the function returns and the error shows up at every caller instead of inside the function.

4. Model states with unions, not optional bags

A common beginner design is one object with lots of optional fields:

TypeScript
// Avoid: which combinations are valid?
interface Request {
  loading: boolean;
  data?: string[];
  error?: string;
}

This type allows nonsense such as { loading: true, data: [...], error: 'oops' }, and every reader has to guess which fields go together. A discriminated union lists the valid states and nothing else:

TypeScript Impossible states become unrepresentable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Inside each case, TypeScript knows exactly which fields exist, so there are no ?. checks and no guessing. The never line in default makes the function fail to compile if someone adds a fifth state and forgets to handle it.

The same thinking applies to choosing between enums and literal unions: for most code, a union of string literals ('light' | 'dark') or an as const object is simpler than an enum and needs no runtime code (Enums covers the trade-offs).

5. Make data readonly by default

Most bugs involving shared data are "someone changed it when I didn't expect". Mark parameters and stored data readonly unless the code really mutates it. A function that takes readonly Item[] promises not to change its argument, and the compiler enforces the promise:

TypeScript readonly parameters catch accidental mutation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Inside cheapestFirst, calling items.sort(...) (which mutates) is a compile error, because readonly Item[] has no sort method. toSorted (ES2023) returns a new array, so it's allowed. For deeper techniques see Readonly and Immutability.

6. Reach for assertions last

as, the non-null operator ! and // @ts-ignore all tell the compiler "trust me". Each one is a spot where the compiler stops protecting you. Better options, in order of preference:

  1. Narrow with a check the compiler understands (if (user), typeof, in, a type guard).
  2. Use satisfies to check an object against a type without widening it (The satisfies Operator).
  3. Annotate a variable so assignments are checked.
  4. Only then assert, with a comment explaining why it's safe.

When you must silence an error, prefer // @ts-expect-error with a reason over // @ts-ignore: it fails once the error is gone, so stale suppressions don't pile up.

7. Don't over-engineer types

Type-level programming is powerful (Advanced Type-Level Programming), but every clever type is code that teammates must read and the compiler must evaluate. Signs you've gone too far: error messages ten lines long, types nobody else can change, a type that tries to validate an email address. Prefer simple, named types; write a small runtime check instead of a 40-line conditional type; and keep the clever generics inside libraries, where type tests protect them.

Other mistakes that come up again and again

  • Thinking types exist at runtime. if (value instanceof User) only works for classes; interfaces and type aliases are erased. Use type guards for plain objects.
  • Using Function, Object, {} or String. Function accepts anything callable with any arguments, {} accepts every value except null and undefined, and String is the wrapper object. Write (x: number) => void, object, Record<string, unknown> and string.
  • Optional chaining everywhere. a?.b?.c?.d on values that are never missing hides real bugs and confuses readers. Fix the type instead.
  • Overusing !. map.get(key)! crashes later, far from the cause, when the key is missing. Check once and handle the missing case.
  • Exporting giant "god" interfaces. Smaller types combined with &, Pick or unions are easier to reuse and test.

The six most common errors

Here are the errors you'll meet most often, all in one program. It fails on purpose, so nothing runs; only the error list appears:

TypeScript The usual suspects (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler reports:

TEXT
main.ts(8,7): error TS2322: Type 'string' is not assignable to type 'number'.
main.ts(9,12): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
main.ts(10,22): error TS2339: Property 'nmae' does not exist on type 'User'.
main.ts(11,16): error TS7006: Parameter 'text' implicitly has an 'any' type.
main.ts(13,13): error TS18048: 'found' is possibly 'undefined'.
main.ts(14,13): error TS2532: Object is possibly 'undefined'.

Read each line as file(line,column): code: message. The column points at the exact expression. What they mean and how to fix them:

Code Means Usual fix
TS2322 A value doesn't fit the declared type of a variable, property or return Fix the value, or the declared type if it was wrong; don't widen to any
TS2345 An argument doesn't fit a parameter Convert the value first (Number(text)), or check the function's signature
TS2339 The property doesn't exist on that type Usually a typo; otherwise narrow the union first, or add the property to the type
TS7006 A parameter has no type and none can be inferred Annotate it; callbacks passed directly to typed functions are inferred automatically
TS18048 A named value might be undefined Check it (if (found)), use ?. or ??, or return early
TS2532 An unnamed expression (like users[0].email) might be undefined Same fixes; store it in a variable first if you want TS18048's clearer message

TS18047 ("possibly 'null'") and TS18049 ("possibly 'null' or 'undefined'") are the siblings of TS18048. Here is the same program with every error fixed properly, without a single assertion:

TypeScript The same program, fixed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Every fix keeps the type information intact: conversions make values match, an annotation gives text a real type, and narrowing (if (found), ?., ??) handles the missing cases instead of hiding them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does const data: any = JSON.parse('{"n":"5"}'); console.log(data.n + 1); print?

    With any, the compiler checks nothing. data.n is the string '5', so + 1 concatenates and prints 51. Typing the result as unknown would force a check first.
  2. 2. Which error code means a named variable might be undefined?

    TS18048 reads "'x' is possibly 'undefined'." for a named value. TS2532 is the version for unnamed expressions.
  3. 3. A function parameter is typed readonly string[]. What happens if the function calls list.push('x')?

    readonly T[] (ReadonlyArray) has no mutating methods, so push, sort and splice don't exist on it. It's a compile-time guarantee only; nothing changes at runtime.
  4. 4. Why is a discriminated union usually better than one interface with many optional fields?

    Each member of the union describes one valid state, so impossible combinations can't be built, and switching on the tag gives each branch exactly the right fields.
  5. 5. Why prefer // @ts-expect-error over // @ts-ignore?

    @ts-expect-error demands an error on the next line. When the code is fixed, it fails with "Unused '@ts-expect-error' directive", reminding you to remove it.

Summary

  • Use strict: true plus noUncheckedIndexedAccess and exactOptionalPropertyTypes; fix errors instead of disabling flags.
  • Type outside data as unknown and validate it once at the boundary; never let any spread.
  • Let inference handle locals; annotate parameters, exported return types and empty collections.
  • Model states as discriminated unions with an exhaustive never check; prefer literal unions to enums in most code.
  • Make parameters and stored data readonly and use non-mutating methods like toSorted.
  • Prefer narrowing and satisfies over as and !; use @ts-expect-error with a reason when you must suppress.
  • Keep types simple; the six common errors (TS2322, TS2345, TS2339, TS7006, TS18048, TS2532) are almost always fixed by correcting the value, annotating, or narrowing.

Next: Project: Typed To-Do CLI