TypeScript Constructor Overload with Empty Constructor

Daniel Hitzel :

Why is it not allowed to have separate constructor definitions in TypeScript?
To have e.g. two constructors, I need to write my code like this.

constructor(id: number)
constructor(id: number, name?: string, surname?: string, email?: string) {
    this.id = id;
    this.name = name;
    this.surname = surname;
    this.email = email;
}

Thereby I need to put ? after the parameters that are not required in the first constructor.

Why can't I write it like this?

constructor(id: number) {
    this.id = id;
}

constructor(id: number, name: string, surname: string, email: string) {
    this.id = id;
    this.name = name;
    this.surname = surname;
    this.email = email;
}

So that for both constructors all parameters are mandatory.

Moreover, if I need to have an empty constructor things get even weirder, since I need to mark every parameter with a ?.

constructor()
constructor(id?: number, name?: string, surname?: string, email?: string) {
    this.id = id;
    this.name = name;
    this.surname = surname;
    this.email = email;
}

Why does TypeScript differs from common languages like C# or Python here?

I would expect it to work like this.

constructor() {

}
constructor(id: number, name: string, surname: string, email: string) {
    this.id = id;
    this.name = name;
    this.surname = surname;
    this.email = email;
}

So you can pass none parameter or must pass all parameters.

Aaron Beall :

Because your constructor implementation is called by all your overload constructors. (Technically, at runtime there's only one constructor function that gets called with the various overload argument signatures.)

Imagine it like this:

overload_constructor(id:string) {
    implementation_constructor(id);
}

implementation_constructor(id:string, name?:string, age?:number) {
    // ...
}

Thinking of it this way, overload_constructor could not call implementation_constructor unless name and age are optional.

Also see Basarat's answer, the implementation isn't exposed for public usage by the type checker (though at runtime it's the "real" constructor used in JS). If you want to only allow (), (id), or (id, name, surname, email) as the only valid call signatures you would do it like this:

constructor()
constructor(id: number)
constructor(id: number, name: string, surname: string, email: string)
constructor(id?: number, name?: string, surname?: string, email?: string) {
    this.id = id;
    this.name = name;
    this.surname = surname;
    this.email = email;
}

Note that in the implementation all parameters are optional, but that signature is not exposed when compiling and you can only use these these calls:

new Foo()
new Foo(1)
new Foo(1, "a", "b", "c")

Not, for example:

new Foo(1, "a")

Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.

En caso de infracción, por favor [email protected] Eliminar

Editado en
0

Déjame decir algunas palabras

0Comentarios
Iniciar sesiónRevisión de participación posterior

Artículos relacionados

Implicit constructor versus "empty" constructor

Class constructor type in typescript?

Typescript: constructor overloading

TypeScript constructor - ambient contexts error

Creating property inside constructor with Typescript

Does empty constructor is created although another constructor was explicitly written?

Does C++ guarantee this enum vs int constructor overload resolution?

Sobrecarga de constructor de TypeScript con constructor vacío

Initialize generic type with non-empty constructor

How to initialize List<E> in empty class constructor?

kotlin + aws lambda requiring empty constructor

Error with Inheritance and TypeScript: X is not a constructor function type

El mejor lugar para declarar constructor - TypeScript

A way to clean up class constructor in TypeScript?

Specify that the return type is a constructor function or class in typescript

Constructor de TypeScript - error de contextos ambientales

Asignar parámetros de constructor de TypeScript

Tipo de constructor de TypeScript seguro

TypeScript: obtener typeof genérico constructor

Patrón de constructor usando interfaces TypeScript

Use typescript to dynamically set class property in constructor

Typescript: How to initialise a class property outside constructor

El mejor lugar para declarar constructor - TypeScript

Ampliación del constructor en TypeScript

Typescript interfaces and promise return an object/constructor?

Constructor Kotlin vs Constructor

Why does my operator + overload call my copy constructor despite being passed by reference?

C++: no matching function for call: why is an empty constructor needed?

How does `type Constructor<T> = Function & { prototype: T }` apply to Abstract constructor types in TypeScript?

TOP Lista

CalienteEtiquetas

Archivo