Dependent constraints
Concept and syntax
A generic constraint can depend on another type parameter. In set<T,K extends keyof T>(obj:T,key:K,value:T[K]), the selected key determines the permitted value type. This is most precise for a specific key; a union key can loosen the relation, so validate dynamic correlated pairs carefully.
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 set<T,K extends keyof T>(x:T,k:K,v:T[K]){x[k]=v;}const item={id:1,label:"tea"};set(item,"id",7);set(item,"label","coffee");console.log(item.id,item.label);Expected output:
7 coffeeCommon mistake
Intentionally invalid; compile separately and do not execute.
function set<T,K extends keyof T>(x:T,k:K,v:T[K]){x[k]=v;}set({id:1},"id","7");Expected diagnostic: TS2345. For key id, T[K] is number. Pass a numeric value.
Practice and recap
Add a boolean field and use set with a compatible value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dependent 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 set<T,K extends keyof T>(x:T,k:K,v:T[K]){x[k]=v;}const item={id:1,label:"tea"};set(item,"id",7);set(item,"label","coffee");console.log(item.id,item.label);Which diagnostic and explanation match the rejected example under the lesson settings?
function set<T,K extends keyof T>(x:T,k:K,v:T[K]){x[k]=v;}set({id:1},"id","7");