Key iteration
Concept and syntax
A mapped type iterates over a union of property keys using [K in Keys]. With keyof T it derives keys from a source contract. The result is a type shape, not a loop that creates an object.
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 Flags<T>={[K in keyof T]:boolean}; type F=Flags<{read:string;write:number}>;const f:F={read:true,write:false}; console.log(f.read,f.write);Expected output:
true falseCommon mistake
Intentionally invalid; compile separately and do not execute.
type Flags<T>={[K in keyof T]:boolean}; type F=Flags<{read:string;write:number}>;const f:F={read:true};Expected diagnostic: TS2741. The mapped write property remains required.
Practice and recap
Add a delete key to the source type.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Key iteration — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Key iteration is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Flags<T>={[K in keyof T]:boolean}; type F=Flags<{read:string;write:number}>;const f:F={read:true,write:false}; console.log(f.read,f.write);Which diagnostic and explanation match the rejected example under the lesson settings?
type Flags<T>={[K in keyof T]:boolean}; type F=Flags<{read:string;write:number}>;const f:F={read:true};What must a Flags<{a:number; b:string}> literal include?