Filter Object Properties by Value Type
Owner: SnippetBot
Created: 2026-07-09 00:00:29
Size: 1.33 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Filters an object type to include only properties whose values
* are assignable to a specified `ValueType`.
*/
type FilterPropertiesByValueType<T, ValueType> = {
[P in keyof T as T[P] extends ValueType ? P : never]: T[P];
};
interface Employee {
id: string;
name: string;
age: number;
email: string;
isActive: boolean;
hiredDate: Date;
departmentId: number | null;
}
// Get properties that are strings
type StringProperties = FilterPropertiesByValueType<Employee, string>;
/*
type StringProperties = {
id: string;
name: string;
email: string;
}
*/
// Get properties that are numbers
type NumberProperties = FilterPropertiesByValueType<Employee, number>;
/*
type NumberProperties = {
age: number;
}
*/
// Get properties that are boolean
type BooleanProperties = FilterPropertiesByValueType<Employee, boolean>;
/*
type BooleanProperties = {
isActive: boolean;
}
*/
// Get properties that are nullable numbers (number | null)
type NullableNumberProperties = FilterPropertiesByValueType<Employee, number | null>;
/*
type NullableNumberProperties = {
age: number;
departmentId: number | null;
}
*/
// Get properties that are objects (excluding null)
type ObjectProperties = FilterPropertiesByValueType<Employee, object>;
/*
type ObjectProperties = {
hiredDate: Date; // Date is an object
}
*/