Sobes.tech
Middle+

const X = { a: 1, b: 2, c: 3, d: 4 } function getProperty<T>(obj: T, key: keyof T) { // Type the function return obj[key] } getProperty(X, 'a') // no error getProperty(X, 'e') // error: key 'e' is not a key of object X getProperty({ name: 'Sergey' }, 'name') // no error getProperty(1, 1) // Error. First argument must be an object (not a function or primitive)

sobes.tech AI

Answer from AI

To type the function getProperty so that:

  • The first argument is an object (not a primitive and not a function),
  • The second argument is a key of that object,
  • The return value corresponds to the property type by the key,

you can use conditional types and constraints in TypeScript.

Example of type definition:

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

Here:

  • T extends object guarantees that obj is an object,
  • K extends keyof T guarantees that key is a key of object T,
  • The return type T[K] corresponds to the type of the value by the key.

Thus, calls like:

getProperty(X, 'a'); // OK
getProperty(X, 'e'); // Error, 'e' is not a key of X
getProperty({ name: 'Sergey' }, 'name'); // OK
getProperty(1, 1); // Error, 1 is not an object

This ensures strict typing and prevents errors at compile time.

const X = { a: 1, b: 2, c: 3, d: 4 } function… - sobes.tech