CodexBloom - Programming Q&A Platform

TypeScript scenarios TS2322 when using a mapped type with conditional properties in a class

👀 Views: 4 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-04
typescript generics mapped-types classes

I've encountered a strange issue with I'm optimizing some code but After trying multiple solutions online, I still can't figure this out. I'm working with a TypeScript behavior (TS2322) when trying to define a class that utilizes a mapped type with conditional properties. My goal is to create a class that has a property `data` which varies its type based on the `type` property. Here's a simplified version of what I have: ```typescript type DataType = 'string' | 'number'; type DataMap<T extends DataType> = { [K in T]: K extends 'string' ? string : number; }; class DataContainer<T extends DataType> { type: T; data: DataMap<T>[T]; constructor(type: T, data: DataMap<T>[T]) { this.type = type; this.data = data; } } const stringData = new DataContainer('string', 'Hello World'); const numberData = new DataContainer('number', 42); ``` However, when I attempt to instantiate `DataContainer`, I get the following behavior: ``` behavior TS2322: Type 'string' is not assignable to type 'DataMap<T>[T]'. ``` I tried to adjust the type of the `data` property and even created a separate interface for managing the data types, but it hasn't resolved the scenario. The behavior message indicates that TypeScript isn't correctly inferring the type for `data` based on the value of `type`. My TypeScript version is 4.5.4. Is there a way to properly structure the class to avoid this type behavior? Or am I misunderstanding how mapped types and generics should work together in this context? This is part of a larger application I'm building. What's the best practice here? I'm coming from a different tech stack and learning Typescript. Any suggestions would be helpful. I'm working with Typescript in a Docker container on Windows 11. Any pointers in the right direction?