Sure, here’s the translation: “Typescript使用泛型的方法签名”

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

Typescript use method signature from generics

问题

可以像这样做吗?这将非常有帮助。使用泛型的方法签名:

class Foo<Parent extends Foo> {
    public bar<U extends Parameters<Parent.bar>>(x: U) {
    }
}
英文:

Is it possible to do something like this? It would help quite a lot. Us the method signature from generics

class Foo&lt;Parent extends Foo&gt; {
    public bar&lt;U extends Parameters&lt;Parent.bar&gt;&gt;(x: U) {
    }
}

答案1

得分: 1

以下是您要翻译的代码部分:

class Foo<Parent extends { bar: (...a: any[]) => any }> {
    public bar<U extends Parameters<Parent['bar']>>(x: U) {
    }
}

Playground链接

您还可能对这个将参数展开到bar函数的版本感兴趣:

class Foo<Parent extends { bar: (...a: any[]) => any }> {
    public bar(...x: Parameters<Parent['bar']>) {
    }
}

Playground链接


<details>
<summary>英文:</summary>

You can&#39;t if you want `Parent` to extend `Foo`, since that would cause a circular dependency in the type, but you can do it if you constrain `Parent` to something else with a `bar`:

```ts
class Foo&lt;Parent extends { bar: (...a: any[]) =&gt; any}&gt; {
    public bar&lt;U extends  Parameters&lt;Parent[&#39;bar&#39;]&gt;&gt;(x: U) {
    }
}

Playground Link

You might also be interested in this version that spreads the arguments back to the bar function:

class Foo&lt;Parent extends { bar: (...a: any[]) =&gt; any}&gt; {
    public bar(...x: Parameters&lt;Parent[&#39;bar&#39;]&gt;) {
    }
}

Playground Link

huangapple
  • 本文由 发表于 2020年1月6日 23:47:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615049.html
匿名

发表评论

匿名网友

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

确定