Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Better type support for Components #71

@anderoonies

Description

@anderoonies

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');

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions