Skip to content
This repository has been archived by the owner on Jun 1, 2022. It is now read-only.

Clean up typings related to component props #207

Merged
merged 1 commit into from
Jul 2, 2020

Conversation

robertlong
Copy link
Member

This PR is based on the work by @krazyjakee in #205. I've tried to get typechecking working properly for all component props with the minimal boilerplate.

This is the result:

// Note you must pass TestComponent (the type of your component) as the generic type
// for props to be typed correctly.
class TestComponent extends Component<TestComponent> {
  // If you are using strict typing you will need to use ! (non-null assertion operator)
  // or ? (optional property). Default properties are set in the constructor for you based on
  // the type of the property or user defined default
  boolProperty!: boolean; 
  optionalNumberProperty?: number;

  static schema = {
    boolProperty: { type: Types.Boolean },
    optionalNumberProperty: { type: Types.Number, default: undefined }
  };
}

// Creating a component via the component constructor:

const component = new TestComponent({ boolProperty: true }); // Properties are type checked and optional

component.boolProperty === true;

if (component.optionalNumberProperty !== undefined) {
  component.optionalNumberProperty += 1;
}

// Creating a component via entity.addComponent:

const world = new World();

const entity = world.createEntity()
  .addComponent(TestComponent, { boolProperty: true }) // Properties are type checked and optional

const entityComponent = entity.getComponent(TestComponent);

entityComponent.boolProperty === true;

if (entityComponent.optionalNumberProperty !== undefined) {
  entityComponent.optionalNumberProperty += 1;
}

static schema: ComponentSchema;
static isComponent: true;
constructor(props?: P | false);
constructor(props?: Partial<Omit<C, keyof Component<any>>> | false);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there was a way to do Partial<Pick<C, keyof C.schema>> that would be even more ideal since the component constructor looks at the component schema keys for props to set.

@fernandojsg fernandojsg merged commit c0ea632 into dev Jul 2, 2020
@fernandojsg fernandojsg deleted the typescript-component-defs branch July 2, 2020 23:29
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants