Sobes.tech
Middle+

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") const getObjField = <T, K extends keyof T>(obj: T, key: K) => { return obj[key] }

sobes.tech AI

Answer from AI

In the first version, the getObjField function parameters have the type any, which does not provide type checking and can lead to errors, for example, when accessing a non-existent key.

In the second version, a generic with the constraint K extends keyof T is used, which guarantees that the key indeed exists in the obj object. This increases safety and ease of use of the function.

Example:

 type 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"); // type string
const value2 = getObjField(user, "age");  // type number
// const value3 = getObjField(user, "test"); // Compilation error, key "test" does not exist in Obj

Thus, the second version of the function ensures type safety and prevents errors at compile time.

type Obj = { name: string age: number } const… - sobes.tech