TypeScript Class with Multiple Constructors and Method Overloading Results in Confusion
I've been researching this but I'm upgrading from an older version and I'm converting an old project and I'm learning this framework and Could someone explain I’m working with an scenario with my TypeScript class which has multiple constructors and overloaded methods... I defined a class called `User` that can be instantiated either with a username or with both a username and an email. Here’s a snippet of my code: ```typescript class User { username: string; email?: string; constructor(username: string); constructor(username: string, email: string); constructor(username: string, email?: string) { this.username = username; if (email) { this.email = email; } } getDetails(): string { return `User: ${this.username}` + (this.email ? `, Email: ${this.email}` : ''); } } const user1 = new User('john_doe'); const user2 = new User('jane_doe', 'jane@example.com'); console.log(user1.getDetails()); // Expected: User: john_doe console.log(user2.getDetails()); // Expected: User: jane_doe, Email: jane@example.com ``` While the class compiles and runs fine, I’m getting an unexpected behavior when I try to create a user with an incorrect number of arguments: ```typescript const user3 = new User(); // behavior: Expected 1 or 2 arguments, but got 0. ``` This is expected, but what’s confusing me is that I also want to allow instantiation with just an email and have the username default to `'guest'`. So I modified my constructor, but now I’m struggling with how to handle the overloads properly to accommodate this new requirement. Here’s what I tried: ```typescript constructor(username?: string, email?: string) { this.username = username || 'guest'; if (email) { this.email = email; } } ``` However, this seems to mess up the typing. Now, when I try to create a user just with an email, TypeScript throws an behavior: ```typescript const user4 = new User(undefined, 'guest@example.com'); // behavior: Argument of type 'undefined' is not assignable to parameter of type 'string'. ``` How can I implement this correctly while maintaining overloads? What’s the best way to handle default values in this scenario while ensuring the type safety that TypeScript provides? My team is using Typescript for this REST API. This issue appeared after updating to Typescript 3.11. Has anyone dealt with something similar? I'm working in a Ubuntu 22.04 environment. Thanks, I really appreciate it! I appreciate any insights! I'm working with Typescript in a Docker container on Linux. This is my first time working with Typescript latest. Any help would be greatly appreciated!