Last active
May 20, 2019 08:03
-
-
Save hasparus/49aebf5073786e6e50df569d63b61a80 to your computer and use it in GitHub Desktop.
Used UnionToIntersection to get Entity type from _all components_ query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// components.ts | |
type Component = Components[keyof Components]; // Health | Transform | |
interface Components { /* add new components to this interface in separate files */ } | |
// health.ts | |
type Health = number & { __brand: 'Health' }; | |
interface Components { | |
health: Health; | |
} | |
// transform.ts | |
class Transform { }; | |
interface Components { | |
transform: Transform; | |
} | |
// entity.ts | |
type Entity = { | |
id: number; | |
}; | |
type EntityWithComponents<ComponentKeys extends (keyof Components)[]> = | |
Entity & { | |
[P in ComponentKeys[number]]: Components[P] | |
}; | |
declare function entityWith<ComponentKeys extends (keyof Components)[]>(components: ComponentKeys): EntityWithComponents<ComponentKeys>; | |
const x = entityWith(['health', 'transform']); | |
type X = typeof x; // 🎉 Entity & { health: Health; transform: Transform; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TypeScript Playground:
https://www.typescriptlang.org/play/index.html#src=%2F%2F%20components.ts%0D%0Atype%20Component%20%3D%20Components%5Bkeyof%20Components%5D%3B%20%2F%2F%20Health%20%7C%20Transform%0D%0A%0D%0Ainterface%20Components%20%7B%20%2F*%20add%20new%20components%20to%20this%20interface%20in%20separate%20files%20*%2F%20%7D%0D%0A%0D%0A%2F%2F%20health.ts%0D%0Atype%20Health%20%3D%20number%20%26%20%7B%20__brand%3A%20'Health'%20%7D%3B%0D%0A%0D%0Ainterface%20Components%20%7B%0D%0A%20%20%20%20health%3A%20Health%3B%20%0D%0A%7D%0D%0A%0D%0A%2F%2F%20transform.ts%0D%0Aclass%20Transform%20%7B%20%7D%3B%0D%0A%0D%0Ainterface%20Components%20%7B%0D%0A%20%20%20%20transform%3A%20Transform%3B%0D%0A%7D%0D%0A%0D%0A%0D%0A%2F%2F%20entity.ts%0D%0Atype%20Entity%20%3D%20%7B%0D%0A%20%20%20%20id%3A%20number%3B%0D%0A%7D%3B%0D%0A%0D%0Atype%20EntityWithComponents%3CComponentKeys%20extends%20(keyof%20Components)%5B%5D%3E%20%3D%0D%0A%20%20%20%20Entity%20%26%20%7B%0D%0A%20%20%20%20%20%20%20%20%5BP%20in%20ComponentKeys%5Bnumber%5D%5D%3A%20Components%5BP%5D%0D%0A%20%20%20%20%7D%3B%0D%0A%0D%0Adeclare%20function%20entityWith%3CComponentKeys%20extends%20(keyof%20Components)%5B%5D%3E(components%3A%20ComponentKeys)%3A%20EntityWithComponents%3CComponentKeys%3E%3B%0D%0A%0D%0Aconst%20x%20%3D%20entityWith(%5B'health'%2C%20'transform'%5D)%3B%0D%0A%0D%0Atype%20X%20%3D%20typeof%20x%3B%20%2F%2F%20%F0%9F%8E%89%20Entity%20%26%20%7B%20health%3A%20Health%3B%20transform%3A%20Transform%3B%20%7D