TypeScript for JS devs - types that pay off immediately

TypeScript for JS devs - types that pay off immediately

TL;DR: Add types where bugs cluster: API inputs and outputs, domain models, and function boundaries. Use narrowing, discriminated unions, and utility types to get safety with low friction.

Where types help most

  • Parsing and validating API responses.
  • Domain models that flow through many functions.
  • Public functions used by several modules.

Narrowing patterns

function isUser(x: unknown): x is { id: string } {
  return typeof x === "object" && x !== null && "id" in x;
}

function getId(x: unknown) {
  if (isUser(x)) return x.id;
  return "unknown";
}

Discriminated unions

type Ok = { type: "ok"; value: number };
type Err = { type: "err"; message: string };

type Result = Ok | Err;

function handle(r: Result) {
  if (r.type === "ok") return r.value;
  return 0;
}

Utility types that matter

type Id = Pick<User, "id">;
function call<F extends (...a: any[]) => any>(f: F): ReturnType<F> { /* ... */ }

Migration tips

  • Start with strict on new modules.
  • Type the edges first, not every local variable.
  • Use any as a pressure release valve while refactoring, then remove it.

FAQ

When is any acceptable
Temporarily, to keep momentum during a refactor. Track and remove it later.

Does TS help in Node and the browser
Yes. It catches interface mismatches and makes large codebases easier to change.

Cast this in your project

Image credit: Photo by cottonbro studio: https://www.pexels.com/photo/person-using-a-silver-laptop-7441740/

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.