-
Notifications
You must be signed in to change notification settings - Fork 31
Open
Description
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');Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels