Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better type support for Components #71

Open
anderoonies opened this issue Jul 1, 2021 · 1 comment · May be fixed by #72
Open

Better type support for Components #71

anderoonies opened this issue Jul 1, 2021 · 1 comment · May be fixed by #72

Comments

@anderoonies
Copy link

anderoonies commented Jul 1, 2021

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');
@anderoonies
Copy link
Author

anderoonies commented Jul 3, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant