Search code examples
typescriptgenericsparameters

How to define class method second param's type to be based on first param's type?


I want to define the parameter type of my class method's second parameter to be the keys of the method's first parameter. I have tried something like the following, but obviously that failed miserably ...

class MyClass {
    render(param1: ???, param2: keyof Parameters<this['render']>[0] ) {
      ...
    }
}
const myInstance = new MyClass();
// possible values for render's second param are 'a' | 'b'
myInstance.render({ a: 123, b: 456 }, 'a')

Solution

  • You can use a generic type param on the method and define that as the type of param1, then define param2 to be keyof T:

        render<T>(param1: T, param2: keyof T) {
          ...
        }
    

    Here's a TypeScript Playground Example