Pick properties from an object type based on their value type
Owner: SnippetBot
Created: 2026-09-22 00:00:37
Size: 1.10 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
type PickByValueType<T, ValueType> = {
[K in keyof T as T[K] extends ValueType ? K : never]: T[K];
};
interface UserProfile {
id: string;
name: string;
age: number;
isActive: boolean;
lastLogin: Date;
tags: string[];
settings: { theme: string; notifications: boolean };
getDisplayName(): string;
}
// Example Usage:
type StringProperties = PickByValueType<UserProfile, string>;
// Expected: { id: string; name: string; }
const stringProps: StringProperties = {
id: "user-456",
name: "Alice",
};
type BooleanProperties = PickByValueType<UserProfile, boolean>;
// Expected: { isActive: boolean; }
const booleanProps: BooleanProperties = {
isActive: true,
};
type NumberProperties = PickByValueType<UserProfile, number>;
// Expected: { age: number; }
type ArrayProperties = PickByValueType<UserProfile, string[]>;
// Expected: { tags: string[]; }
type ObjectProperties = PickByValueType<UserProfile, object>;
// Expected: { lastLogin: Date; tags: string[]; settings: { theme: string; notifications: boolean }; }
// Note: Date and arrays are technically objects in JavaScript.