Class design in TypeScript

typescript

Solution

This works as well, and is perhaps closer to the original:

class Class1 {

    id:number;

    constructor(s: string) {
        (n:number) => {
            this.id = n;
        }(s.length)
    }
}

var t:Class1 = new Class1("HELLO");
console.log("Class1ID: " + t.id); // Output = Class1 ID: 5

For reference, here's the output JS:

var Class1 = (function () {
    function Class1(s) {
        var _this = this;
        (function (n) {
            _this.id = n;
        })(s.length);
    }
    return Class1;
})();
var t = new Class1("HELLO");
console.log("Class1 ID: " + t.id);

Update

If you have to be able to call the constructor with just an ID, then I think you'll have to use a factory method, as Steve has suggested. And, since I don't think TS constructors can be private, if you need that method to be private you'll have to dispense with the constructor altogether and use a pair of factory methods. The first instance might look something like this:

class Class1 {

    constructor(public id:number) {} // Public, unfortunately.

    static Fabricate(s:string):Class1 {
        return new Class1(s.length);
    }
}

var classA:Class1 = new Class1(1);
var classB:Class1 = Class1.Fabricate("Hello");

console.log(classA.id);   // "1"
console.log(classB.id);   // "5"

And the second something like this:

class Class1 {

    id:number;

    private static fabricate(n:number):Class1 {
        var class1:Class1 = new Class1();
        class1.id = n;
        return class1;
    }

    static Fabricate(s:string):Class1 {
        return fabricate(s.length);
    }
}

var classA:Class1 = Class1.Fabricate("Hello");

console.log(classA.id);   // "5"

Problem

I'm struggling to implement some class design in TypeScript considering that it doesn't support multiple constructors with different prototypes. Basically, I would like to design classes with a public constructor that takes some parameters, and an 'internal' constructor (only used within the library). The public constructor would call the internal one. In C#, it would look like this: ``` public class Class1 { internal Class1(int id) { } public Class1(string s) : this(s.Length) { } } ``` Any idea how I would translate this to TypeScript? Thanks in advance!

Original source