CodexBloom - Programming Q&A Platform

TypeScript - guide with type narrowing in a generic function utilizing mapped types

👀 Views: 64 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
typescript generics mapped-types TypeScript

Quick question that's been bugging me - I'm integrating two systems and I've been working on this all day and I'm integrating two systems and I'm working with a question with type narrowing in a generic function that uses mapped types in TypeScript... I have a simple utility that takes an object and a key, and I'm trying to return the value of that key while preserving the type of the object. However, when I try to narrow down the type based on the key, it doesn't seem to work as intended. Here's what I have: ```typescript type Data = { id: number; name: string; active: boolean; }; function getValue<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } const data: Data = { id: 1, name: 'Alice', active: true }; const nameValue = getValue(data, 'name'); // This works fine const idValue = getValue(data, 'id'); // This also works fine const activeValue = getValue(data, 'active'); // This works too ``` However, I tried to create a mapped type to transform `Data`, where I want to only allow certain keys based on a condition: ```typescript type MappedData<T> = { [K in keyof T]: T[K] extends boolean ? 'boolean' : 'other'; }; function getMappedValue<T>(obj: T, key: keyof MappedData<T>): MappedData<T>[typeof key] { return obj[key]; } ``` The question arises when I call `getMappedValue(data, 'active')`. It gives me a type behavior saying that 'active' is not assignable to the type of 'other'. It seems like the type inference is not handling the mapped type correctly. I've tried adjusting the mapped type and using `as` assertions, but nothing seems to resolve the type incompatibility. Any insights on how I can correctly infer the types with this mapped type or if there's a more suitable approach to achieve what I want? I'm using TypeScript 4.6.2. Hoping someone can shed some light on this. I'm working with Typescript in a Docker container on Ubuntu 20.04. What's the correct way to implement this? My development environment is CentOS. Any help would be greatly appreciated!