CodexBloom - Programming Q&A Platform

TypeScript: Type Inference implementing Mapped Types and Conditional Types

πŸ‘€ Views: 19 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
typescript conditional-types mapped-types TypeScript

I'm learning this framework and I'm working on a personal project and I'm working with a challenging scenario with TypeScript where I'm trying to create a mapped type that utilizes conditional types, but the type inference isn't behaving as I expected... I have a utility type that should map an object type to its keys, but when I use it in conjunction with a conditional type, I'm getting unexpected results. Here's a simplified version of what I'm trying to achieve: ```typescript type User = { id: number; name: string; email?: string; }; type UserFields<T> = { [K in keyof T]-?: T[K] extends string ? K : never }[keyof T]; type UserStringFields = UserFields<User>; ``` I expect `UserStringFields` to resolve to the string literals "name" and "email". However, when I compile this, TypeScript throws the following behavior: ``` Type 'never' is not assignable to type 'string'. ``` I've tried various combinations of mapped types and utility types but haven't been able to resolve the inference correctly. I've also ensured my TypeScript version is 4.4, and I've checked the `strict` mode settings in my `tsconfig.json`. Here’s the relevant part of it: ```json { "compilerOptions": { "strict": true, "target": "ES2020" } } ``` I even attempted to simplify the utility type to this: ```typescript type UserStringFieldsSimple = { [K in keyof User]-?: User[K] extends string ? K : never }[keyof User]; ``` Still no luck! Can anyone guide to understand what's going wrong here? Any insights into how I can fix the type inference scenario would be greatly appreciated. Thanks in advance! I'm working on a CLI tool that needs to handle this. Any help would be greatly appreciated! Thanks for any help you can provide!