Middle+
const X = { a: 1, b: 2, c: 3, d: 4 } function getProperty(obj, key) { // Type the function return obj[key] } getProperty(X, 'a') // no error getProperty(X, 'r') // error, key r is not a key for object X getProperty({ name: 'Sergey' }, 'name') // no error
sobes.tech AI
Answer from AI
To type the getProperty function so that the key is strictly from the object's keys, you can use generics with a key constraint via keyof:
const X = { a: 1, b: 2, c: 3, d: 4 };
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
getProperty(X, 'a'); // OK
getProperty(X, 'r'); // Error: 'r' is not a key of X
getProperty({ name: 'Sergey' }, 'name'); // OK
Here, K extends keyof T guarantees that the key key belongs to the object obj, and the return type corresponds to the type of the value at that key.