如何重写react-hook-form内部的UseFormSetValue类型(无需patch-package)?
重写react-hook-form的UseFormSetValue类型并让内部引用生效
问题场景
我尝试重写react-hook-form中的UseFormSetValue类型,已创建override.d.ts测试文件,内容如下:
declare global { module "react-hook-form" { export * from "react-hook-form"; export type UseFormSetValue<TFieldValues extends FieldValues> = unknown; } }
当前问题:自己导入该类型时重写生效,但react-hook-form内部使用该类型时,重写并未被应用。希望实现让内部使用也能生效的类型重写,且避免使用patch-package这类工具。
解决方案
调整类型声明文件写法
移除declare global包裹,直接扩展react-hook-form模块。TypeScript的模块合并特性会将你的声明与原模块合并,直接覆盖原有类型:import type { FieldValues } from "react-hook-form"; declare module "react-hook-form" { export type UseFormSetValue<TFieldValues extends FieldValues> = unknown; }无需添加
export * from "react-hook-form",模块合并会自动保留原模块其他类型,仅替换你重写的部分。确保声明文件被TypeScript加载
在tsconfig.json的include数组中加入声明文件路径,保证编译时被识别:{ "compilerOptions": { /* 你的项目配置 */ }, "include": [ "src/**/*", "./override.d.ts" // 替换为实际文件路径 ] }刷新TypeScript服务验证效果
重启TypeScript语言服务(如VSCode中按Ctrl+Shift+P选择"TypeScript: Restart TS Server"),此时无论外部导入还是react-hook-form内部使用UseFormSetValue,都会应用你重写后的类型。
内容的提问来源于stack exchange,提问作者Reuben Drummond
相关产品推荐
相关产品推荐

