Constrain Property Access With keyof

Read and patch object properties through keys constrained by keyof, so wrong key names and mismatched value types both fail compilation.

TypescriptData Integrity

Code

typescriptsnippet
28 lines
interface DeployConfig {
  retries: number;
  endpoint: string;
  debug: boolean;
}

// keyof 约束键名,Config[K] 联动值类型:键名与值类型同时受检
function read<K extends keyof DeployConfig>(config: DeployConfig, key: K): DeployConfig[K] {
  return config[key];
}

function patch<K extends keyof DeployConfig>(config: DeployConfig, key: K, value: DeployConfig[K]): DeployConfig {
  return { ...config, [key]: value };
}

const config: DeployConfig = { retries: 3, endpoint: '/api', debug: false };

console.log(read(config, 'retries'));
console.log(read(config, 'endpoint'));

const updated = patch(config, 'retries', 5);
console.log('updated:', updated.retries, 'original:', config.retries);

// @ts-expect-error: 'debug' 需要 boolean
patch(config, 'debug', 'yes');

// @ts-expect-error: 'timeouts' 不在 DeployConfig 的键里
read(config, 'timeouts');

How the snippet works

Constrain Property Access With keyof reduces to the functions read and patch.

The result comes back as an object carrying config.

Using it

Running the file prints labeled results such as updated: — each operation’s effect is visible in the output.

The call returns config.

Key statements

function patch<K extends keyof DeployConfig>(config: DeployConfig, key: K, value: DeployConfig[K]): DeployConfig {
return { ...config, [key]: value };
}
function read<K extends keyof DeployConfig>(config: DeployConfig, key: K): DeployConfig[K] {
return config[key];
}

Interactive Tools for This Topic

FAQ

Does `read` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `read`, `patch` at load time.