TypeScript: Mapped Type with Conditional Properties Not Behaving as Expected
I'm maintaining legacy code that I'm working with TypeScript 4.5 and trying to create a mapped type that conditionally adds properties to an object based on a boolean flag. My goal is to have a `User` type that can either include the `email` property or not, depending on the value of a `hasEmail` boolean property. I thought using a mapped type with a conditional would work, but I'm running into issues. Here's what I have so far: ```typescript type UserBase = { id: number; name: string; }; type User<HasEmail extends boolean> = HasEmail extends true ? UserBase & { email: string } : UserBase; const userWithEmail: User<true> = { id: 1, name: 'Alice', email: 'alice@example.com', // This works }; const userWithoutEmail: User<false> = { id: 2, name: 'Bob', // email: 'bob@example.com', // This should cause a type behavior, but it doesn't }; ``` When I try to define `userWithoutEmail`, TypeScript does not throw an behavior when I attempt to include the `email` property, which is not the behavior I expected. I've also tried using `Pick` to conditionally exclude the `email` property like this: ```typescript type UserWithoutEmail = Pick<UserBase, 'id' | 'name'>; ``` But this isn't giving me the expected results either. I want to ensure that the `email` property really is excluded from the `User` type when `HasEmail` is `false`. Is there a better approach to achieve this? Any help with correcting or improving this implementation would be greatly appreciated! This is my first time working with Typescript latest. Any advice would be much appreciated.