typescript / intermediate
Snippet
Narrowing Unknown Data Payload with Type Predicates
Type predicates allow functions to act as custom type guards. By specifying `data is UserProfile` as the return type, TypeScript automatically narrows the type of `payload` inside conditional blocks whenever the guard returns `true`.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
interface UserProfile {id: string;role: "admin" | "member";}function isUserProfile(data: unknown): data is UserProfile {return (typeof data === "object" &&data !== null &&"id" in data &&typeof (data as Record<string, unknown>).id === "string" &&"role" in data &&((data as Record<string, unknown>).role === "admin" || (data as Record<string, unknown>).role === "member"));}function processPayload(payload: unknown) {if (isUserProfile(payload)) {console.log(`Valid user: ${payload.id} (${payload.role})`);}}
Breakdown
1
function isUserProfile(data: unknown): data is UserProfile {
Defines a custom type guard function returning a type predicate `data is UserProfile`.
2
typeof data === "object" && data !== null &&
Ensures the input value is a non-null object before inspecting properties.
3
"id" in data && typeof (data as Record<string, unknown>).id === "string" &&
Verifies that property `id` exists and is of type string.
4
if (isUserProfile(payload)) {
Narrows `payload` from `unknown` to `UserProfile` inside this conditional block.