TypeScript: implementing Type Inference in Utility Types Using Conditional Types
I'm a bit lost with I'm converting an old project and I'm dealing with I'm confused about I'm experiencing a frustrating scenario with TypeScript's type inference when using utility types and conditional types... I have a `User` interface and a utility type `OptionalKeys<T>` which is intended to make specific properties of an object optional based on a condition. However, when I apply this utility type to my `User` interface, the inferred types seem to be incorrect. Here's a simplified version of my `User` interface: ```typescript interface User { id: number; name: string; email: string; age?: number; } ``` And the utility type I'm trying to create: ```typescript type OptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? K : never; }[keyof T]; ``` The goal is to retrieve the keys of properties that are optional in the `User` interface. I then try to create a type that makes these optional keys actually optional: ```typescript type OptionalUser = Pick<User, OptionalKeys<User>>; ``` However, when I try to use `OptionalUser`, I get the following behavior: ``` Type 'undefined' is not assignable to type 'string'. ``` I've also tried explicitly defining `OptionalKeys` as follows: ```typescript type OptionalKeys<T> = { [K in keyof T]: T[K] extends undefined ? K : never; }[keyof T]; ``` But that doesn't resolve the scenario. I expected `OptionalUser` to have the `age` property as optional, but it seems like TypeScript is not inferring the types correctly. I've been using TypeScript version 4.5.4, and I'm not sure if there's a specific configuration in my `tsconfig.json` that's affecting type inference. I've confirmed that `strict` is set to `true`. Has anyone faced a similar scenario, or can someone point me in the right direction to resolve this? What am I doing wrong? My development environment is Linux. Any help would be greatly appreciated! I'm working on a mobile app that needs to handle this. Any examples would be super helpful. My development environment is macOS. Cheers for any assistance! The project is a service built with Typescript. Could this be a known issue? This is for a application running on CentOS.