TypeScript Reference

Run TypeScript examples for validating JSON, preserving optional values, and handling discriminated unions.

Run the examples

With TypeScript and Node.js installed, save each example as example.ts. Run tsc --strict example.ts, followed by node example.js.

Validate parsed JSON at runtime

Assign parsed JSON to unknown. Check its shape and field types before using it. The guard narrows the TypeScript type after the runtime checks succeed.

typescript
type Config = { port: number };

function isConfig(value: unknown): value is Config {
  return typeof value === "object" && value !== null &&
    "port" in value && typeof value.port === "number";
}

const input: unknown = JSON.parse('{"port":8080}');
if (isConfig(input)) console.log(input.port);

Expected output

8080

Common mistake

A type assertion (as Config) performs no validation. Handle invalid JSON syntax separately from invalid field values.

Official documentation

Preserve false and zero when setting defaults

Use the nullish coalescing operator when only null and undefined should trigger a default.

typescript
type Options = { retries?: number; enabled?: boolean };

const options: Options = { retries: 0, enabled: false };
console.log(options.retries ?? 3, options.enabled ?? true);

Expected output

0 false

Common mistake

The || operator also falls back for 0, false, and an empty string. Consider whether each is meaningful input.

Official documentation

Use a result type for success and failure

Give each branch a distinct literal tag. When you check the tag, TypeScript exposes only the fields available for that branch.

typescript
type Result =
  | { kind: "ok"; value: number }
  | { kind: "error"; message: string };

function readCount(text: string): Result {
  return /^\d+$/.test(text)
    ? { kind: "ok", value: Number(text) }
    : { kind: "error", message: "Expected digits" };
}

for (const input of ["12", "12px"]) {
  const result = readCount(input);
  console.log(result.kind === "ok" ? result.value : result.message);
}

Expected output

12
Expected digits

Common mistake

An object with optional value and error fields can represent an impossible state where both fields are absent. Separate variants make that state invalid.

Official documentation

Related tools