TypeScript Type Utilities and Functions
Here are some utility types and functions that I have found useful that are not enough to qualify publishing them into a library but I end up copy-pasting for use in between projects.
Custom Utility Types
-
FilteredType
- A Type that filters down theTypeToFilter
to a tuple of types that match theCondition
type FilteredType<TypeToFilter, Condition> = { [K in keyof TypeToFilter]: TypeToFilter[K] extends Condition ? K : never }[keyof TypeToFilter]
-
Constructable<T>
- a type that matches a type that can be instantiated, i.e. classestype Constructable<T> = new (...args: any[]) => T
-
ValueOf
- For a given type, this filters down to a tuple of the values of the typetype ValueOf<T> = T[keyof T]
-
DeepPartial
- Makes all nested properties of an object to be Optional.type DeepPartial<T> = T extends Object ? { [K in keyof T] : DeepPartial<T[K]> } : T
Utility Functions
-
The
filterKeys
type filters a type based on the regex provided. This is useful if you would like to get the keys of an object that meet a certain criteria.function filterKeys<T extends Object, K extends RegExp>(source: T, regExp: K): FilteredType<T, K>[]{ return Object.keys(source).filter((key) => regExp.test(key) ) as FilteredType<T, K>[] }
-
getConstructorParams
- this returns a list of the constructor parameters of the class. We can also utilize theConstructable<T>
type we defined earlier and pass the class into the function:/* as defined above in the utility types */ type Constructable<T> = new (...args: any[]) => T function getConstructorParams<T>(constructor: Constructable<T>) { const params = constructor.toString().match(/\(([^)]*)\)/)?.[1] return params?.split(',').map((param) => param.trim()) ?? [] }