Type Guards Bridging Runtime Checks

Turn ad-hoc runtime checks into reusable type guards so parsed JSON flows into typed code paths without repeated assertions.

TypescriptSecurity Boundaries

Code

typescriptsnippet
25 lines
interface Task {
  title: string;
  done: boolean;
}

function isTask(value: unknown): value is Task {
  if (typeof value !== 'object' || value === null) return false;
  const v = value as Record<string, unknown>;
  return typeof v.title === 'string' && typeof v.done === 'boolean';
}

function parseTasks(raw: string): Task[] {
  const parsed: unknown = JSON.parse(raw);
  if (!Array.isArray(parsed)) return [];
  // filter + 收窄:守卫让 unknown 数组安全变成 Task[]
  return parsed.filter(isTask);
}

const good = parseTasks('[{"title":"ship","done":false},{"title":42}]');
console.log(good);

// 内建守卫的用法
const mixed: (string | number)[] = [1, 'a', 2, 'b'];
const strs = mixed.filter((x): x is string => typeof x === 'string');
console.log(strs);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

[ { title: 'ship', done: false } ]
[ 'a', 'b' ]

How the code works

Type Guards Bridging Runtime Checks reduces to the functions isTask and parseTasks.

The result is a fresh construction, so callers can keep their originals.

What to watch for

  • The guard typeof value !== 'object' || value === null short-circuits the flow with an early return when its condition holds.

Applying it

The primary signature is function isTask(value: unknown)

Statements that matter

const strs = mixed.filter((x): x is string => typeof x === 'string');
return typeof v.title === 'string' && typeof v.done === 'boolean';
if (typeof value !== 'object' || value === null) return false;

Interactive Tools for This Topic

FAQ

Does `isTask` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `isTask`, `parseTasks` at load time.