如何在具有泛型的函数上使用 ReturnType

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

How to use ReturnType on a function that also has a generic

问题

以下是您要翻译的内容:

这段代码片段演示了问题:

function foo<T>(init: T) {
    let data = init;
    return {
        getData: () => data,
        update: (u: T) => { data = u }
    }
}

let obj: ReturnType<typeof foo>;

obj = foo<boolean>(true); // 错误

演示

错误信息如下:

类型 '{ getData: () => boolean; update: (u: boolean) => void; }' 不能分配给类型 '{ getData: () => unknown; update: (u: unknown) => void; }'。
属性 'update' 的类型不兼容。
类型 '(u: boolean) => void' 不能分配给类型 '(u: unknown) => void'。
参数 'u' 和 'u' 的类型不兼容。
类型 'unknown' 不能分配给类型 'boolean'。

问题出在以下代码中:

let obj: ReturnType<typeof foo>;

我没有定义泛型,这导致 T 变成了 unknown。您可以按照以下方式修复:

let obj: ReturnType<typeof foo>;

obj = foo<unknown>(true);

所以我的问题是,是否可能在以下代码中以某种方式定义泛型 T 并将其设置为布尔值,例如:

let obj: ReturnType<typeof foo>;
英文:

The following code snippet demonstrates the problem:

function foo&lt;T&gt;(init: T) {
    let data = init;
    return {
        getData: () =&gt; data,
        update: (u: T) =&gt; { data = u }
    }
}

let obj: ReturnType&lt;typeof foo&gt;;

obj = foo&lt;boolean&gt;(true); // ERROR

DEMO

The error is:

Type &#39;{ getData: () =&gt; boolean; update: (u: boolean) =&gt; void; }&#39; is not assignable to type &#39;{ getData: () =&gt; unknown; update: (u: unknown) =&gt; void; }&#39;.
  Types of property &#39;update&#39; are incompatible.
    Type &#39;(u: boolean) =&gt; void&#39; is not assignable to type &#39;(u: unknown) =&gt; void&#39;.
      Types of parameters &#39;u&#39; and &#39;u&#39; are incompatible.
        Type &#39;unknown&#39; is not assignable to type &#39;boolean&#39;.

What happens is that in

let obj: ReturnType&lt;typeof foo&gt;;

I don't the define the generic, which makes T -> unknown. So I can fix this as follows

let obj: ReturnType&lt;typeof foo&gt;;

obj = foo&lt;unknown&gt;(true);

So my question is, is it possible to somehow define the generic T in

let obj: ReturnType&lt;typeof foo&gt;;

and set it to, for example, a boolean?

答案1

得分: 1

有一种传递泛型而不调用函数本身的语法:

const func = <T>(arg: T): void => {}

// (arg: boolean) => void
const booleanFunc = func<boolean>

// (arg: string) => void
const stringFunc = func<string>

你可以使用相同的语法获取返回类型:

ReturnType<typeof foo<boolean>>
英文:

There is a syntax for passing a generic without calling the function itself:

const func = &lt;T&gt;(arg: T): void =&gt; {}

// (arg: boolean) =&gt; void
const booleanFunc = func&lt;boolean&gt;

// (arg: string) =&gt; void
const stringFunc = func&lt;string&gt;

You can apply the same syntax to get the return type:

ReturnType&lt;typeof foo&lt;boolean&gt;&gt;

huangapple
  • 本文由 发表于 2023年7月11日 04:55:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76657288.html
匿名

发表评论

匿名网友

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

确定