I tried to create a class with two constructors and find out that TypeScript does not allow this, but it allows you to overload the constructor, well, I tried this and got an error:
Build: overload signature is incompatible with the implementation of the function.
My code is:
interface IShoppingListItem { name: string; amount: number; } export class ShoppingListItem implements IShoppingListItem{ name: string; amount: number; constructor(item: IShoppingListItem); constructor(name: string, amount: number) { this.name = name; this.amount = amount; } copy() {
I have two questions: firstly, why I can not overload the constructor, I think I'm doing something wrong.
But my second question and more interaction, I know, I am a constructor that gets additional values. Can I (not with the code inside the method!) Create a condition for my constructor, which can verify that one of the two given values should exist, while loading the signature is optional, for example:
constructor(item?: IShoppingListItem, name?: string, amount?: number) { //make a condition that item or name and amount must exist this.name = name; this.amount = amount; }
Thanks.
typescript
Nir schwartz
source share