TypeScript theorytheory 0/50 · 0%
Types · medium

33. Working with JSON & unknown

Safely handling data whose shape isn't guaranteed at compile time.

`JSON.parse` returns `any`, which silently disables type checking — a common source of runtime bugs when the actual JSON doesn't match assumptions. Assigning to `unknown` and validating before use is safer.

ts
interface Config { chainId: number; rpcUrl: string; }

function isConfig(value: unknown): value is Config {
  return (
    typeof value === "object" && value !== null &&
    typeof (value as any).chainId === "number" &&
    typeof (value as any).rpcUrl === "string"
  );
}

function loadConfig(raw: string): Config {
  const parsed: unknown = JSON.parse(raw);
  if (!isConfig(parsed)) throw new Error("Invalid config");
  return parsed; // narrowed to Config
}

Libraries like zod or io-ts automate this pattern by deriving both a runtime validator and a static type from one schema, avoiding the duplication of writing an interface and a hand-written guard separately.

Check your understanding

  1. 1. What type does `JSON.parse` return?

  2. 2. Why assign the parsed result to `unknown` instead of using the `any` directly?

  3. 3. What do schema-validation libraries like zod typically provide?