4

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.

0

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.