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.
Code
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 === nullshort-circuits the flow with an earlyreturnwhen 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.