Skip to content

Instantly share code, notes, and snippets.

@hasparus
Last active May 20, 2019 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hasparus/49aebf5073786e6e50df569d63b61a80 to your computer and use it in GitHub Desktop.
Save hasparus/49aebf5073786e6e50df569d63b61a80 to your computer and use it in GitHub Desktop.
Used UnionToIntersection to get Entity type from _all components_ query
// 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; }
@hasparus
Copy link
Author

hasparus commented May 20, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment