获取TypeScript类中泛型函数的返回类型如何?

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

How to get the return type of a generic function inside a class with TypeScript?

问题

使用Angular的类型化表单,我想获取FormBuilder.group<T>()的返回类型(R),以便可以像这样使用R:FormGroup<R>

为此,我尝试了以下代码:

type R = ReturnType<FormBuilder['group<T>']>;

但这是无效的TypeScript。

是否有一种方法可以让R成为特定泛型参数T的group函数的返回类型?

英文:

With Angular's typed forms, I want to get the return type (R) of FormBuilder.group&lt;T&gt;() such that I can use this R like this: FormGroup&lt;R&gt;.

For this I tried:

type R = ReturnType&lt;FormBuilder[&#39;group&#39;]&lt;T&gt;&gt;;

Which is invalid Typescript.

Is there a way to get R to be the return type of the group function for a specific generic parameter T?

答案1

得分: 0

以下是翻译好的部分:

"这不可能做到(也许是疏忽了?)而不首先降到表达级别:"

declare const _group: FormBuilder["group"];
type R = ReturnType<typeof _group<{ foo: "bar" }>>; // ok

Playground


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

It&#39;s not possible to do this (maybe it&#39;s an oversight?) without dropping to the expression level first:

```ts
declare const _group: FormBuilder[&quot;group&quot;];
type R = ReturnType&lt;typeof _group&lt;{ foo: &quot;bar&quot; }&gt;&gt;; // ok

Playground

huangapple
  • 本文由 发表于 2023年5月26日 00:57:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334649.html
匿名

发表评论

匿名网友

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

确定