Keyof
Concept and syntax
keyof T produces a union of property keys known on T. For an ordinary finite object these are literal key types. Index signatures can yield broader string or number key types. keyof is a compile-time operation, not a list of runtime keys; it does not call Object.keys.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
type Item={id:number;label:string};function showKey(k:keyof Item){return k;}console.log(showKey("id"),showKey("label"));Expected output:
id labelCommon mistake
Intentionally invalid; compile separately and do not execute.
type Item={id:number;label:string};const key:keyof Item="missing";Expected diagnostic: TS2322. missing is not a known key of Item. Choose id or label.
Practice and recap
Add an optional property and see whether its name is included in keyof.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Keyof — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Item={id:number;label:string};function showKey(k:keyof Item){return k;}console.log(showKey("id"),showKey("label"));Which diagnostic and explanation match the rejected example under the lesson settings?
type Item={id:number;label:string};const key:keyof Item="missing";