首页 > 解决方案 > 如何包装来自 React useState 钩子的 setValue 调用并保持相同的类型签名?

问题描述

如果我有类似的代码const [value, setValue] = useState<string>("");,则类型为React.Dispatch<React.SetStateAction<string>>.

我想拥有一些东西const wrappedSetValue = (value: string) => setValue(value.toUpperCase());。我该如何编写它以使其保持相同的类型签名setValue

标签: reactjstypescriptreact-hooks

解决方案


您可以使用typeofTS 关键字来推断 的类型setValue并对其进行注释wrappedSetValue

const wrappedSetValue: typeof setValue = (value: string) => setValue(value.toUpperCase());

老实说,这有点欺骗 cusReact.Dispatch<React.SetStateAction<string>>实际上是一个类型别名,归结为

(value: string | ((s: string) => string)) => void;

因此,上面的实现只覆盖了类型签名的一半。

我不确定这是你想要的,但为了完成签名声明,你还应该实现允许作为参数传入函数的另一半:

const wrappedSetValue: typeof setValue = (value: string | ((s: string) => string)) => 
  typeof value == 'string' ? setValue(value.toUpperCase()) : setValue(value);

推荐阅读