reactjs - 如何包装来自 React useState 钩子的 setValue 调用并保持相同的类型签名?
问题描述
如果我有类似的代码const [value, setValue] = useState<string>("");
,则类型为React.Dispatch<React.SetStateAction<string>>
.
我想拥有一些东西const wrappedSetValue = (value: string) => setValue(value.toUpperCase());
。我该如何编写它以使其保持相同的类型签名setValue
?
解决方案
您可以使用typeof
TS 关键字来推断 的类型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);
推荐阅读
- swift - 快速设置单元格委托会出错
- ksqldb - 运行某些查询时重新启动 KSQL-Server
- angular - 在更新和验证子组件后运行 ControlValueAccessor validate
- clickhouse - ClickHouse ,选择 top n 并按主键排序的问题
- c - 浅层和深层析构函数?
- android - 固定 TabLayout 中每页的选项卡数
- go - 如何测试忽略golang中的一些测试文件?
- react-native - TabNavigator 子屏幕如何引用父 StackNavigator?
- apache-karaf - 无法使用 undertow 服务器保护 7.3 fuse 控制台
- google-api - 无法为 Google Docs API 设置适当的范围