Middle+
const X = { a: 1, b: 2, c: 3, d: 4 } function getProperty(obj, key) { // Task to type the function return obj[key] } getProperty(X, 'a') // no error getProperty(X, ' ') // error: key is not a valid key for object X getProperty({ name: 'Sergey' }, 'name') // no error
sobes.tech AI
Answer from AI
To type the getProperty function so that it accepts an object and a key that definitely exists in that object, you can use generics and the keyof operator in TypeScript:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const X = { a: 1, b: 2, c: 3, d: 4 };
getProperty(X, 'a'); // OK
getProperty(X, ' '); // Error: type " " is not a key of object X
getProperty({ name: 'Sergey' }, 'name'); // OK
Here, K extends keyof T guarantees that the key key belongs to the object obj. This prevents passing non-existent keys and allows for obtaining the correct return type.