ape-ecs
ape-ecs copied to clipboard
Better type support for Components
I'm trying to get TypeScript to be aware of the properties
of a Component, but because Components' properties are static
, it's not possible to create a generic Component type from those properties.
I put together a TypedComponent
definition that gets what I'm after, but it's pretty messy and I'm not sure it's an accepted pattern in TypeScript.
Let me know your thoughts, I'm going to continue developing with it and see how it feels, but so far it's been a useful type.
// types
declare type Constructor<T> = new (...args: any[]) => T;
export function TypedComponent<TProperties extends {}, TBase extends Component>(
props: TProperties
): typeof Component &
Constructor<TBase & TProperties> & {
properties: TProperties;
};
// implementation
function TypedComponent(props) {
const newClass = class TypedComponent extends Component {};
newClass.properties = {...props};
return newClass;
}
Then in my component definition, then in a system:
// usage:
class Position extends TypedComponent({x: 0, y: 0}) {}
assert(typeof Position.properties.x === 'number');
// ...
const position: Position = entity.getOne(Position);
assert(typeof position.x === 'number');
some updates after working on this for a bit, i've added a TypedComponent
type, so the TypedComponent
factory is now:
declare type Constructor<T> = new (...args: any[]) => T;
export function TypedComponent<TProperties extends {}, TBase extends Component>(
props: TProperties
): typeof Component &
TypedComponent<TProperties> &
Constructor<TBase & TProperties>;
type TypedComponent<TProperties extends {}> = Component & {
properties: TProperties;
};
I've also found this type to be helpful on Entity
when using this TypedComponent
:
addComponent<T extends Component>(
properties: { type: T } & (T extends TypedComponent<infer TProperties>
? TProperties
: { [other: string]: any })
): Component | undefined;
i imagine the same would be true of the createEntity
constructor with c: {type: Component}
etc