This also works, and 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);
For reference, here's the JS output:
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 should be able to call the constructor with only an identifier, I think you will have to use the factory method, as Steve suggested. And, since I don't think TS constructors can be private, if you need this method to be private, you have to do without the constructor and use a couple 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 is 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);
source share