michaelolof / typescript-mix

A tweaked implementation of TypeScript's default applyMixins(...) idea using ES7 decorators
https://www.npmjs.com/package/typescript-mix
86 stars 8 forks source link

Mixins don't work with getters #4

Closed trentjones21 closed 6 years ago

trentjones21 commented 6 years ago

I just started using this library today. I love it so far. Thanks for maintaining it.

From what I can tell, typescript getters don't work with mixins (at least in my specific case). Here is an example I am trying to get to work.

class EmployableMixin {
  config: any;
  get companyId(): string {
    return this.config.companyId; // TypeError: Cannot read property 'companyId' of undefined
  }
}

class Employee {
  @use(EmployableMixin)

  config: any;
  constructor(config) {
    this.config = config;
  }
}

const employee = new Employee({companyId: '12345'});
console.log(employee.companyId) // error

However, if I edit the mixin to use a regular function rather than a getter, the error goes away:

class EmployableMixin {
  config: any;
  getCompanyId(): string {
    return this.config.companyId; // no error
  }
}

class Employee {
  @use(EmployableMixin)

  config: any;
  constructor(config) {
    this.config = config;
  }
}

const employee = new Employee({companyId: '12345'});
console.log(employee.getCompanyId()) // 12345

I realize I'm probably doing something unconventional by trying to access the config object in the mixin class. But if it works with a regular function I feel like it should work with a getter as well. Do you know if this would be possible to fix? I'm happy to help out with a pull request. I just wanted to get your thoughts first.

michaelolof commented 6 years ago

By default @use decorators ignore properties and only mixes in methods. That is why the first example fails

That said I can see why you'd want to use getters. Would look into it. But for now you can keep using methods as they won't give any problems.

michaelolof commented 6 years ago

Support for getters and setters added from typescript-mix@3.1.3

Also feel free to make pull requests and contribute.

Thanks.