IK
Interview Knowledge Book
Topics
Practice
Examples
Playground
RU
browser
Unknown boundary guard
Model the TypeScript habit of parsing unknown data before using it in application code.
index.js
/** * TypeScript version: * type User = { id: number; name: string }; * function isUser(value: unknown): value is User { ... } */ function isUser(value) { return typeof value === 'object' && value !== null && typeof value.id === 'number' && typeof value.name === 'string'; } for (const payload of [{ id: 42, name: 'Ada' }, { id: '42', name: 'Ada' }]) { if (isUser(payload)) { console.log(`${payload.name}:${payload.id}`); } else { console.log('Invalid user payload'); } }
Run
Stop
Reset