Reputation: 20308
I have a class like:
class Shape {
attrs : any = {};
getWidth() : number {
return this.attrs.x * 2;
}
/*some code*/
}
The class have a LOT of getters and setters methods like getProperty()
and setProperty()
. Almost all of them works in same way but with different properties. To avoid a lot of code duplication in class definition I add such methods dynamically:
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function addGetter(constructor, attr, defaultValue) : void {
var method = 'get' + capitalize(attr);
constructor.prototype[method] = function() {
var val = this.attrs[attr];
return val === undefined ? defaultValue : val;
};
}
// then add a lot of getters in fast way
addGetter(Shape, 'x');
// now we have shape.getX();
addGetter(Shape, 'y');
// now we have shape.getY();
It works really good for javascript. But what about typesctipt? I can not do the same thing as I will have an error:
var shape = new Shape();
shape.getX(); // Property 'getX' does not exist on type 'Shape'.
I know that I can create "fake" method in class definition then overwrite it. But looks ugly:
class Shape {
attrs : any = {};
getWidth() : number {
return (this.attrs.x || 0) * 2;
}
// fake method
getX() : number {
return 0;
}
/*some code*/
}
// then overwrite
addGetter(Shape, 'x');
Do you now any good solutions for this use case?
Upvotes: 1
Views: 3510
Reputation: 275927
function addGetter(constructor, attr, defaultValue) : void
This is effectively a mixin
. There isn't a good story about mixins in TypeScript at the moment. There is documentation of how to type it : https://github.com/Microsoft/TypeScript/wiki/Mixins
You basically declare that these members exist but don't provide an implementation.
class Shape {
attrs : any = {};
getWidth() : number {
return (this.attrs.x || 0) * 2;
}
// declared only
getX: ()=> number;
/*some code*/
}
// then define
addGetter(Shape, 'x');
Mixins are on the roadmap for 2.0 : http://github.com/Microsoft/TypeScript/wiki/Roadmap#20 Also you can start a discussion here : http://github.com/Microsoft/TypeScript/issues It would be great if you can come up with a proposal
Upvotes: 5