React TypeScript如何为外部npm包扩展补充类型定义
问题场景
在React TypeScript项目中引入npm包react-microsoft-login,向组件的children属性传入自定义按钮节点时,触发TypeScript报错:
property 'children' does not exist on type 'intrinsicattributes & microsoftloginprops'
对应实现代码如下:
<MicrosoftLogin clientId={office_clientId} graphScopes={graphScopes} prompt={'select_account'} useLocalStorageCache={true} authCallback={authHandler} buttonTheme={'dark'} children={ <Tooltip title={'One Drive'}> <IconButton onClick={(e:any) => { folderClicked = true; }} color='inherit' > <Office style={{ height: '20px', width: '20px' }} /> </IconButton> </Tooltip> } />
此前通过直接修改node_modules目录下react-microsoft-login的类型声明文件、补充children: any类型定义的方式可以临时解决问题,但修改node_modules内文件的方案会在依赖重新安装后失效,无法持久化,需要在项目本地目录扩展外部npm包类型、无需修改node_modules源码的可行方案。
可行方案
方案1:TypeScript模块扩展(推荐,官方支持)
这是TypeScript原生提供的模块类型补充能力,修改会持久保存在项目目录中,重装依赖不会失效:
- 在项目
src目录(或tsconfig.json中include配置覆盖的目录)下,新建类型声明文件react-microsoft-login.d.ts - 在文件中写入以下类型扩展代码,不推荐使用
any类型,使用React标准的children类型可获得更准确的类型校验:
import type { ReactNode } from 'react'; import 'react-microsoft-login'; declare module 'react-microsoft-login' { export interface MicrosoftLoginProps { children?: ReactNode; } }
- 保存文件后重启TS服务(VS Code中可通过命令面板执行
TypeScript: Restart TS Server),报错即可消除。
方案2:组件类型断言(兜底方案)
如果因为包的导出格式问题,模块扩展不生效,可以通过类型断言在使用层补全类型,无需修改全局类型:
import MicrosoftLogin from 'react-microsoft-login'; import type { ComponentProps, ReactNode } from 'react'; // 补全children类型后的组件 const PatchedMicrosoftLogin = MicrosoftLogin as React.FC< ComponentProps<typeof MicrosoftLogin> & { children?: ReactNode } >; // 后续使用PatchedMicrosoftLogin替换原组件即可,其余props校验规则和原组件完全一致 <PatchedMicrosoftLogin clientId={office_clientId} graphScopes={graphScopes} prompt={'select_account'} useLocalStorageCache={true} authCallback={authHandler} buttonTheme={'dark'} > <Tooltip title={'One Drive'}> <IconButton onClick={(e:any) => { folderClicked = true; }} color='inherit' > <Office style={{ height: '20px', width: '20px' }} /> </IconButton> </Tooltip> </PatchedMicrosoftLogin>
内容的提问来源于stack exchange,提问作者Vignesh
相关产品推荐
相关产品推荐

