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.
FilteredType
- A Type that filters down the TypeToFilter
to a tuple of types that match the Condition
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. classes
type Constructable<T> = new (...args: any[]) => T
ValueOf
- For a given type, this filters down to a tuple of the values of the type
type 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
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 the Constructable<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()) ?? []}
Last modified on: Thu Jun 29 2023