Safely narrow unknown JSON with type guards
Replace "as any" on parsed JSON with small type guards that check shape at runtime.
- TypeScript
- GreenSnippets
- MIT
- Executed with Node.js 22 (type stripping)
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.
Related snippets
- PHP Tested
Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.
- Python Tested
Sign API requests with HMAC-SHA256
Create and verify a timestamped signature over the method, path and body so requests cannot be forged or replayed.
- JavaScript Tested
Generate secure random IDs and integers
Create UUIDs, random integers in a range and URL-safe tokens with the Web Crypto API instead of Math.random.
- PHP Tested
Generate a secure random token in PHP
Create unpredictable tokens for password resets, API keys and CSRF protection with random_bytes.

