【问题标题】:How can I get return type of generic functions?如何获得泛型函数的返回类型?
【发布时间】:2021-06-16 16:45:17
【问题描述】:

我尝试在 Typescript 中创建存储 useState 返回值的上下文,如下所示:

const SomethingContext = React.createContext<ReturnType<typeof useState<Something>> | undefined>(undefined);

但由于<Something> 类型规范,它会引发语法错误。

如果我在没有类型说明的情况下使用ReturnTypeSomethingContext 会变成React.Context<[unknown, React.Dispatch<unknown>] | undefined>,这是我没想到的,因为unknown

我做错了什么?

更一般地说,我怎样才能获得指定类型的泛型函数的返回类型?

预期行为

一个满足GenericReturnType的类型:

GenericReturnType<Something, useState>[Something, React.Dispatch<Something>]

相关问题

Typescript ReturnType of generic function

【问题讨论】:

  • 我也喜欢这个,因为我的用例:function useMyHook(): ReturnType<typeof useState<string>> { ... };

标签: reactjs typescript web react-hooks


【解决方案1】:

首先useState根本不是类型,不能以泛型的方式传递,因此将GenericReturnType<Something, useState>转为[Something | undefined, React.Dispatch<Something>]是不现实的

第二,useState<T>()的类型等于[T, React.Dispatch<React.SetStateAction<T>>],我很好奇你为什么不直接使用React.Dispatch<React.SetStateAction<T>呢?

【讨论】:

  • 我正在寻找相同问题的答案,但似乎不可能。但是当我来到这里时,我看到你问为什么不使用function useMyHook(): [string, React.Dispatch<React.SetStateAction<string>] 之类的东西。好吧,首先这读起来不好,其次我想对未来的库更改保持安全。因此,如果将来useState 的返回类型发生变化,我也不必更改我的代码。另外我已经安装了库,所以我不必自己编写代码。类型定义遵循相同的规则。该类型存在于库中,所以我不应该自己再写。
  • 我更喜欢这样的东西:function useMyHook(): ReturnType<typeof useState<string>> 读起来更好:Whatever the useState with string returns
猜你喜欢
  • 1970-01-01
  • 2020-03-23
  • 2018-10-04
  • 2019-11-08
  • 2021-05-18
  • 2019-07-19
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多