Last active
May 7, 2022 02:43
-
-
Save John-Paul-R/0b1aee9359a49eb3669c81a4ad5abc66 to your computer and use it in GitHub Desktop.
Utility types for constructing a type from an existing type, including only properties that are of a specified type. Can be applied recursively to child objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type FilteredKeys<T, U> = { [P in keyof T]: T[P] extends U ? P : never }[keyof T]; | |
enum Color { | |
Red, Green, Blue, | |
} | |
type PropsOfType<T, U> = { | |
[K in FilteredKeys<T, U>]: T[K] | |
}; | |
type TestType = { | |
a: boolean; | |
b: number; | |
c: string; | |
d: Color; | |
e: { | |
one: boolean; | |
two: number; | |
} | |
} | |
type FilteredKeysRecursive<T, U> = { [P in keyof T]: T[P] extends U ? P : T[P] extends Record<string, unknown> ? P : never }[keyof T]; | |
type PropsOfTypeRecursive<T, U> = { | |
[K in FilteredKeysRecursive<T, U>]: T[K] extends Record<string, unknown> | |
? PropsOfTypeRecursive<T[K], U> | |
: T[K] | |
}; | |
type TestTypeBoolProps = PropsOfType<TestType, boolean>; | |
type TestTypeBoolPropsRecursive = PropsOfTypeRecursive<TestType, boolean>; | |
const testObj1: TestTypeBoolProps = { | |
a: false | |
} | |
const testObj2: TestTypeBoolPropsRecursive = { | |
a: false, | |
e: { | |
one: false, | |
two: 5, // expected error | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment