Skip to content
GreenSnippets

Safely narrow unknown JSON with type guards

Replace "as any" on parsed JSON with small type guards that check shape at runtime.

TypeScript
function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function hasString<K extends string>(value: unknown, key: K): value is Record<K, string> {
  return isRecord(value) && typeof value[key] === "string";
}

function parseUser(json: string): { name: string } | null {
  let data: unknown;
  try {
    data = JSON.parse(json);
  } catch {
    return null;
  }
  return hasString(data, "name") ? { name: data.name } : null;
}

How it works

JSON.parse and response.json() return any, which silently disables type checking. Treat external data as unknown and narrow it with guards. For anything non-trivial prefer a schema library such as Zod, but these primitives are handy for small cases.