TypeScript

Lesson 02

Narrowing unknown

Check unknown values before using them as trusted application data.

Good Code

parse-settings.ts
type Settings = {
  theme: "light" | "dark";
};

function isSettings(value: unknown): value is Settings {
  return (
    typeof value === "object" &&
    value !== null &&
    "theme" in value &&
    (value.theme === "light" || value.theme === "dark")
  );
}

function readSettings(value: unknown): Settings {
  // The type guard earns trust before returning Settings.
  if (!isSettings(value)) {
    return { theme: "light" };
  }

  return value;
}

Bad Code

parse-settings.ts
type Settings = {
  theme: "light" | "dark";
};

function readSettings(value: unknown): Settings {
  // Double casting skips the runtime proof unknown requires.
  return value as any as Settings;
}

Review Notes

What to review

Good Code

The good version treats incoming data as unknown until a small runtime check proves it has the expected shape.

Bad Code

The bad version tells TypeScript to trust the value without earning that trust, so invalid data can travel through the app as if it were safe.

Takeaways

  • Narrow unknown input to make invalid states harder to express after validation.