如何定义类方法的第二个参数类型基于第一个参数的类型?

huangapple go评论52阅读模式
英文:

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

问题

我想定义我的类方法的第二个参数的参数类型为方法的第一个参数的键。我尝试了类似以下的方式,但显然失败了...

class MyClass {
    render(param1: Record<string, any>, param2: keyof typeof param1 ) {
      // ...
    }
}
const myInstance = new MyClass();
// render的第二个参数的可能值为 'a' | 'b'
myInstance.render({ a: 123, b: 456 }, 'a')
英文:

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&lt;this[&#39;render&#39;]&gt;[0] ) {
      ...
    }
}
const myInstance = new MyClass();
// possible values for render&#39;s second param are &#39;a&#39; | &#39;b&#39;
myInstance.render({ a: 123, b: 456 }, &#39;a&#39;)

答案1

得分: 0

你可以在方法上使用泛型类型参数,并将其定义为param1的类型,然后将param2定义为keyof T

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

这里有一个 TypeScript Playground 示例。

英文:

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&lt;T&gt;(param1: T, param2: keyof T) {
      ...
    }

Here's a TypeScript Playground Example

huangapple
  • 本文由 发表于 2023年2月10日 14:07:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75407494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定