Sobes.tech
Middle+

/ Write type definitions for the function getObjField / type Obj = { name: string age: number } const getObjField = (obj: any, key: any) => { return obj[key] } const user: Obj = { name: "Nik", age: 25 } const value1 = getObjField(user, "name") const value2 = getObjField(user, "age") const value3 = getObjField(user, "test")

sobes.tech AI

Answer from AI

To type the getObjField function so that it accepts an object and a key from that object, and returns the value of the corresponding type, you can use generics and the keyof operator in TypeScript:

interface Obj {
  name: string;
  age: number;
}

const getObjField = <T, K extends keyof T>(obj: T, key: K): T[K] => {
  return obj[key];
}

const user: Obj = { name: "Nik", age: 25 };

const value1 = getObjField(user, "name"); // string
const value2 = getObjField(user, "age");  // number
// const value3 = getObjField(user, "test"); // Compilation error: "test" is not a key of Obj

This approach guarantees that the key exists in the object, and the return type matches the field's type.

/ Write type definitions for the function getObjField… - sobes.tech