capypad
0 day streak
typescript / expert
Snippet

Distributive Conditional Types for Filtering

By leveraging distributive conditional types and the 'never' type, we can create powerful utility types that filter object properties based on their value types. This is essential for clean API contracts and state management.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
type NonFunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? never : K
}[keyof T];
 
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
 
interface UserProfile {
id: string;
age: number;
updateEmail: (email: string) => void;
}
 
type CleanProfile = NonFunctionProperties<UserProfile>;
// Result: { id: string; age: number; }
Breakdown
1
T[K] extends Function ? never : K
If the property is a function, we return 'never'; otherwise, we return the property key name.
2
[keyof T]
Indexed access lookup that collapses the object into a union of its values, effectively removing 'never'.