by Tade0 · 4y ago · 0 comments
Here's a type signature from hell with its usage:
type Component = { type: 'a' } | { type: 'b' };
type FoundComponents<T extends any[]> = T extends [a: infer A] ? [Extract<Component, {type: A}>] :
T extends [a: infer A, ...b: infer B ] ? [Extract<Component, {type: A}>, ...FoundComponents<B>] : never;
export function findComponentSets<T extends Component['type'][]>(components: Component[], ...componentTypes: T ): FoundComponents<T>[];
export function findComponentSets(components: Component[], ...componentTypes: Component['type'][] ): Component[][] { return [] }
It recursively picks outputs types based on the input parameters, so if you call e.g. findComponentSets([], 'a', 'b') the output type will be [{type: 'a'}, {type: 'b'}][].I'm using it in an Entity Component System based game I'm writing to type check the function which receives a flat list of Components and type selectors and outputs a list of tuples with the selected Component types.
findComponentSets(components, 'position', 'hit-box')
.forEach(([position, hitBox]) => system.process(position, hitBox));