using generic params in typescript

the challenge#

interface MyInterface {
  key1: number;
  key2: string;
}

So for example we have the following setup. We have a Typescript interface and object implementing this interface and a function we pass the object and a key, which indicates the field of the object we want to manipulate.

As goodie we also get for that is type completion in VSC. So we get suggestions deppending on the type the object hast.

interface MyInterface {
  key1: number,
  key2: string
}

const obj: MyInterface =
  {
    key1: 1,
    key2: "value"
  };

function myFunction( obj: any, key: string ) {
  // do something here
}

We can easily change our function to use generics:

function myFunction< T >( obj: T, value: keyof T ) {
  // do something here
}

Use the function as follow:

function myFunction< MyInterface >( obj, "key1" );

Or even simpler:

function myFunction( obj, "key1" );