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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With