typescript / intermediate
Snippet
Dynamic Payload Validation with User-Defined Type Guard Predicates
External input from web requests or files comes into TypeScript as unknown. Writing a custom type guard function returning `payload is TargetType` refines untrusted input safely into validated typed interfaces at runtime.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
interface UserProfile {username: string;age: number;}function isUserProfile(payload: unknown): payload is UserProfile {return (typeof payload === "object" &&payload !== null &&typeof (payload as Record<string, unknown>).username === "string" &&typeof (payload as Record<string, unknown>).age === "number");}
Breakdown
1
function isUserProfile(payload: unknown): payload is UserProfile
Declares a type predicate that instructs TypeScript to narrow the argument type if the function returns true.
2
typeof (payload as Record<string, unknown>).username === "string"
Performs runtime assertions on expected object properties before narrowing.