Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to anonymous classes in TypeScript

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?

like image 870
JL235 Avatar asked Oct 12 '12 19:10

JL235


1 Answers

Try this definition of newPersonSex:

var newPersonSex = function (sex: string) {
    return <new (name: string) => Person> <any> function (name: string) {
        return new Person(name, sex);
    }
}

The problem with your code is that functions just have call signatures, not construct signatures. My example above works around this by first asserting that the type of that function is any, and then asserting that the any type is actually a constructor.

Note that the type of newPersonSex will be inferred from its return type so no need to add a function annotation.

like image 151
Brian Terlson Avatar answered Oct 18 '22 23:10

Brian Terlson