Keyof constraints
Concept and syntax
Combine T with K extends keyof T to express that a key must belong to the supplied object. The return type T[K] then describes the selected property. This avoids accepting arbitrary strings and preserves the specific property type at each call.
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.
function get<T,K extends keyof T>(x:T,k:K):T[K]{return x[k];}const item={id:7,label:"tea"};const n:number=get(item,"id");const s:string=get(item,"label");console.log(n,s);Expected output:
7 teaCommon mistake
Intentionally invalid; compile separately and do not execute.
function get<T,K extends keyof T>(x:T,k:K):T[K]{return x[k];}get({id:7},"missing");Expected diagnostic: TS2345. missing does not belong to keyof the inferred object. Select an actual key.
Practice and recap
Use get with a boolean property and verify the inferred type.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Keyof constraints — 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)?
function get<T,K extends keyof T>(x:T,k:K):T[K]{return x[k];}const item={id:7,label:"tea"};const n:number=get(item,"id");const s:string=get(item,"label");console.log(n,s);Which diagnostic and explanation match the rejected example under the lesson settings?
function get<T,K extends keyof T>(x:T,k:K):T[K]{return x[k];}get({id:7},"missing");