I am trying to create a helper function, to add currying, to generate common setups for classes. For example:
class Person {
private name: string;
private sex: string;
constructor (name: string, sex: string) {
this.name = name;
this.sex = sex;
}
}
var newPersonSex = function (sex: string) {
return function (name: string) {
return new Person(name, sex);
}
}
var MalePerson = newPersonSex('male');
var FemalePerson = newPersonSex('female');
So that now when MalePerson and FemalePerson objects are created, it actually just returns a new instance of Person instead.
var m = new MalePerson( 'john' );
In order for the type system allow me to still use 'new', MalePerson needs to be a constructor type. For example: 'new (name:string) => Person'. That also needs to be the return type of the function.
However with those declarations added, I cannot return a function from inside 'newPersonSex'. For example this is invalid:
var newPersonSex = function (sex: string) : new(name:string) => Person {
return function (name: string) {
return new Person(name, sex);
}
}
How can I create and return a new constructor function or class on the fly?