ts怎么把库的类型暴露到项目全局?

作者站长头像
站长
· 阅读数 18
import { FormInstance } from '@arco-design/web-react/es/Form/interface'
...

function test(){
    const FormRef = useRef<FormInstance>(null) // * 指定FormInstance后,FormRef才有了对应的ts类型
    return(
        <Form ref={FormRef}></Form>
    }
}

问题:现在不止有一个页面有这种需求,所以想着把FormInstance拿出来变成全局,不需要每次都要import

现在的做法(不知道是否是标准姿势,求大佬指教):

// * types.d.ts
import { FormInstance } from '@arco-design/web-react/es/Form/interface'

declare global {
  interface CpFormInstance extends FormInstance{}
}
回复
1个回答
avatar
test
2024-07-03

写一个types.d.ts 文件

// * types.d.ts
import { FormInstance as ArcoFormInstance } from '@arco-design/web-react/es/Form/interface'

declare global {
  type GlobalFormInstance = ArcoFormInstance;
}

这样你可以全局用 GlobalFormInstance 类型,就不用每次都去导入:

// In some other file
const FormRef = useRef<GlobalFormInstance>(null);
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容