Skip to content

Instantly share code, notes, and snippets.

@John-Paul-R
Last active May 7, 2022 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save John-Paul-R/0b1aee9359a49eb3669c81a4ad5abc66 to your computer and use it in GitHub Desktop.
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.
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