Sobes.tech
Middle

Task #4: implement a function according to its TypeScript types (the function takes an object and a key of this object, returns the value by the key).

sobes.tech AI

Answer from AI

The function takes an object and a key of that object, returning the value associated with the key. In TypeScript, this can be implemented using generics and the keyof operator to ensure type safety:

function getValue<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// Example usage:
const user = { name: "Alice", age: 30 };
const userName = getValue(user, "name"); // type string
const userAge = getValue(user, "age");   // type number

This way, the function guarantees that the key actually exists in the object and returns a value of the correct type.

Task #4: implement a function according to its… - sobes.tech