3 ms·
Conditional type expression are indeed very powerful and, little known fact, can be used to generate types recursively. Here's a type signature from hell with
by Tade0 5y ago
Conditional type expression are indeed very powerful and, little known fact, can be used to generate types recursively.
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));
- mbrodersen 5y agoThis is an example of Typescript kinda sorta have some of what Dependent Types will give you. The problem is that the Typescript team hasn’t fully embraced this. So instead of implementing Dependent Types (see Agda/Idris/LEAN), the team is kinda sorta implementing parts of it piece wise, inventing different syntax for each feature as they add it. A bit like templates in C++ ended up kinda sorta implementing a Turing complete functional programming language with the worlds worst syntax. It looks as if Typescript is going down the same road. It’s a bit of a mess compared with Dependently Typed languages (Agda/Idris/…)
- chii 5y agoohh that's really interesting. Any chance of open sourcing this as a library?