Conditional property mapping
Concept and syntax
Conditional property mapping chooses each output value type based on its source value type. Here numeric properties become strings while other values keep their types. T[K] is not a naked type parameter, so a union-valued property is tested as a whole.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Format<T>={[K in keyof T]:T[K] extends number?string:T[K]}; type F=Format<{count:number;active:boolean;mix:number|boolean}>;const f:F={count:"2",active:true,mix:3}; console.log(f.count,f.active,f.mix);Expected output:
2 true 3Common mistake
Intentionally invalid; compile separately and do not execute.
type Format<T>={[K in keyof T]:T[K] extends number?string:T[K]}; type F=Format<{count:number;active:boolean;mix:number|boolean}>;const f:F={count:2,active:true,mix:3};Expected diagnostic: TS2322. The numeric count type is transformed to string.
Practice and recap
Extract a helper conditional to distribute over mix.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Conditional property mapping — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Conditional property mapping is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Format<T>={[K in keyof T]:T[K] extends number?string:T[K]}; type F=Format<{count:number;active:boolean;mix:number|boolean}>;const f:F={count:"2",active:true,mix:3}; console.log(f.count,f.active,f.mix);Which diagnostic and explanation match the rejected example under the lesson settings?
type Format<T>={[K in keyof T]:T[K] extends number?string:T[K]}; type F=Format<{count:number;active:boolean;mix:number|boolean}>;const f:F={count:2,active:true,mix:3};What does Format<{mix:number | boolean}>["mix"] evaluate to?