TypeScript Constructor Overload with Empty Constructor

前端 未结 4 1879
春和景丽
春和景丽 2020-12-15 03:30

Why is it not allowed to have separate constructor definitions in TypeScript?
To have e.g. two constructors<

4条回答
  •  爱一瞬间的悲伤
    2020-12-15 04:05

    The last function overload is only used in the implementation and not available publicly. This is shown below:

    class Foo{
        constructor()
        constructor(id?: number) {
        }
    }
    
    const foo1 = new Foo();
    const foo2 = new Foo(123); // Error! : not public
    

    If you want id:number to be available publically ofcourse you can add another overload:

    class Foo{
        constructor()
        constructor(id: number)
        constructor(id?: number) {
        }
    }
    
    const foo1 = new Foo();
    const foo2 = new Foo(123); // Okay
    const foo3 = new Foo('hello'); // Error: Does not match any public overload
    

    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
    

提交回复
热议问题