Why TS use mulple constructure but not NG2


The reason is that TypeScript tries not to do fancy code generation for function overloading (traditional languages do this using name mangling e.g. C++)
So you can pass none parameter or must pass parameters.
Actually you can make the final overload optional but none of the public ones as optional. Consider the following example:
class Foo{ 
    constructor(id: number, name:string)
    constructor(name:string)
    constructor(idOrName?: number|string, name?:string) {
    }
}

const foo1 = new Foo('name'); // Okay
const foo2 = new Foo(123); // Error: you must provide a name if you use the id overload
const foo3 = new Foo(123,'name'); // Okay


Interpreate as

var Foo = /** @class */ (function () {
    function Foo(idOrName, name) {
    }
    return Foo;
}());
var foo1 = new Foo('name'); // Okay
//const foo2 = new Foo(123); // Error: you must provide a name if you use the id overload
var foo3 = new Foo(123, 'name'); // Okay
console.log('1:' + foo1);
console.log('3:' + foo3);

Comments

Popular Posts