Unknown Input Type Guard Hardening
Validate untrusted JSON with unknown-typed inputs and hand-written type guards so every field is checked before it reaches business logic.
Code
interface WebhookEvent {
id: string;
action: 'created' | 'deleted';
payload: { repo: string; stars: number };
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isWebhookEvent(value: unknown): value is WebhookEvent {
if (!isRecord(value)) return false;
if (typeof value.id !== 'string') return false;
if (value.action !== 'created' && value.action !== 'deleted') return false;
if (!isRecord(value.payload)) return false;
if (typeof value.payload.repo !== 'string') return false;
if (typeof value.payload.stars !== 'number' || !Number.isFinite(value.payload.stars)) {
return false;
}
return true;
}
function handle(raw: unknown): string {
// 守卫之后 unknown 收窄为 WebhookEvent,业务代码零 as 断言
if (!isWebhookEvent(raw)) {
return 'rejected: malformed event';
}
return `${raw.id}: ${raw.action} on ${raw.payload.repo} (${raw.payload.stars} stars)`;
}
console.log(handle({ id: 'w1', action: 'created', payload: { repo: 'a/b', stars: 3 } }));
console.log(handle({ id: 'w2', action: 'poked', payload: null }));
console.log(handle('not an object'));Output
Captured from a sandboxed run of this snippet in the build pipeline.
w1: created on a/b (3 stars)
rejected: malformed event
rejected: malformed eventInside the working code
Unknown Input Type Guard Hardening keeps everything in the functions isRecord, isWebhookEvent and handle.
Watch out for
- The guard
typeof value.id !== 'string'short-circuits the flow with an earlyreturnwhen its condition holds.
Putting it to use
The primary signature is function isRecord(value: unknown)
Core lines
return `${raw.id}: ${raw.action} on ${raw.payload.repo} (${raw.payload.stars} stars)`;
return typeof value === 'object' && value !== null && !Array.isArray(value);
if (value.action !== 'created' && value.action !== 'deleted') 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
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `isRecord`, `isWebhookEvent`, `handle` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.