Mapped unions and reverse inference
Concept and syntax
A homomorphic mapping over a union can preserve its alternatives. A mapped input can also allow reverse inference: the compiler infers source property types from corresponding wrapped values. Reverse inference is pattern-dependent, not a general inverse for arbitrary key remapping.
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 Boxes<T>={[K in keyof T]:{value:T[K]}}; function unbox<T>(x:Boxes<T>):T { const result={} as T; for(const k in x)result[k]=x[k].value; return result; }type U=Boxes<{a:number}|{b:string}>;const u:U={b:{value:"tea"}}; const r=unbox({count:{value:3},label:{value:"tea"}}); const n:number=r.count; console.log(n,r.label);Expected output:
3 teaCommon mistake
Intentionally invalid; compile separately and do not execute.
type Boxes<T>={[K in keyof T]:{value:T[K]}}; function unbox<T>(x:Boxes<T>):T { const result={} as T; for(const k in x)result[k]=x[k].value; return result; }type U=Boxes<{a:number}|{b:string}>;const r=unbox({count:{value:3}}); const s:string=r.count;Expected diagnostic: TS2322. The wrapped number inferred count as number, not string.
Practice and recap
Add another wrapped field and verify its inferred type.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Mapped unions and reverse inference — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Mapped unions and reverse inference is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Boxes<T>={[K in keyof T]:{value:T[K]}}; function unbox<T>(x:Boxes<T>):T { const result={} as T; for(const k in x)result[k]=x[k].value; return result; }type U=Boxes<{a:number}|{b:string}>;const u:U={b:{value:"tea"}}; const r=unbox({count:{value:3},label:{value:"tea"}}); const n:number=r.count; console.log(n,r.label);Which diagnostic and explanation match the rejected example under the lesson settings?
type Boxes<T>={[K in keyof T]:{value:T[K]}}; function unbox<T>(x:Boxes<T>):T { const result={} as T; for(const k in x)result[k]=x[k].value; return result; }type U=Boxes<{a:number}|{b:string}>;const r=unbox({count:{value:3}}); const s:string=r.count;Why can unbox infer count as number?