What it is and why to use it
A generic setter can connect a selected object key to the type of value allowed at that key. keyof lists the known keys, and indexed access T[K] looks up the selected property type. This is useful for updating a well-typed configuration object without weakening every value to a broad union.
Common mistakes and limitations
This helper is intended for mutable properties and trusted keys. If the key itself is a union, its value type can also be a union; that does not preserve every runtime correlation. Do not use this signature as a runtime validation or authorisation boundary.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
function set<T, K extends keyof T>(object: T, key: K, value: T[K]): void;Examples
Generic Setters with Correlated Keys and Values
Standalone TypeScript 5.8+ example; expected output is explained below.
function setProperty<T, K extends keyof T>(object: T, key: K, value: T[K]): void {
object[key] = value;
}
const settings = { title: "Draft", attempts: 1 };
setProperty(settings, "attempts", 3);
setProperty(settings, "title", "Ready");
console.log(settings.title + ": " + settings.attempts);- K is constrained to a key of the supplied object.
- Selecting attempts makes T[K] number; selecting title makes it string.
- Both assignments mutate the original object. A fixed literal key receives its matching value type, making simple updates safer.
- Expected output: Ready: 3
Best practices
- This helper is intended for mutable properties and trusted keys. If the key itself is a union, its value type can also be a union; that does not preserve every runtime correlation. Do not use this signature as a runtime validation or authorisation boundary.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook