Constructor Overloading in TypeScript: How to Properly Declare Multiple Variants?
Hi! I just started learning TypeScript and encountered a problem with constructor overloading. The documentation says TypeScript supports function overloading, but I can't get it to work for a class constructor.
I have a `User` class that should accept different sets of parameters:
- Name and age (required)
- Only name (age defaults to 0)
- An object with name and age fields
Here's what I'm trying to do:
```typescript
class User {
name: string;
age: number;
constructor(name: string, age: number);
constructor(name: string);
constructor(obj: {name: string, age: number}) {
this.name = name;
this.age = age;
}
}
```
TypeScript complains: "Type '{name: string, age: number}' is not assignable to type 'string'". I understand that the problem
No answers yet.
Log in to leave an answer