Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript constructor overloading, expecting less arguments than given

Tags:

typescript

I want to have 2 different constructors. One for only an ID, and one for Id, firstname and a boolean value.

Interface: person.ts

export interface Person {
  id: number;
  firstname?: string;
  good?: boolean;
}

Class: Employee.ts

import { Person } from './person';

export class Employee implements Person {

  id: number;

  constructor(id: number);
  constructor(id: number, firstname?: string, public good?: boolean) { }
}

App:

import { Employee } from './employee';

export class AppComponent {
  e1 = new Employee(3); // does work
  e2 = new Employee(2,'Mr Nice', true); // does not work

}

The typescript message is clear: "Expecting 1 arguments but got 3" I thought that when I declare 3 arguments it should automatically work with the second constructor.

like image 354
Mr. Olomu Avatar asked Mar 08 '23 11:03

Mr. Olomu


1 Answers

As per the spec the signature of the implementation is not included in the public type. You could write the following to have both signatures:

export class Employee implements Person {

    id: number;

    constructor(id: number);
    constructor(id: number, firstname?: string, good?: boolean);
    constructor(id: number, public firstname?: string, public good?: boolean) { }
}

Also in this case you don't actually need to have the two overloads. Declaring the last two parameters as optional works just as well :

export class Employee implements Person {
    id: number;
    constructor(id: number, public firstname?: string, public good?: boolean) { }
}
new Employee(10)
new Employee(10, "", true)
like image 138
Titian Cernicova-Dragomir Avatar answered Apr 26 '23 23:04

Titian Cernicova-Dragomir