ecsyjs / ecsy

Entity Component System for javascript
https://ecsyjs.github.io/ecsy/
MIT License
1.11k stars 115 forks source link

Clean up typings related to component props #207

Closed robertlong closed 4 years ago

robertlong commented 4 years ago

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;
}