React+TypeScript中props提示属性未定义、无类型第三方库如何在interface声明类型
React + TypeScript 常见两类问题解决方案
1. props提示属性未定义的解决方法
- 优先检查props是否完成了类型声明。React 组件的所有用到的 props 属性都需要提前在
interface或type中定义,未声明的属性会触发 TypeScript 未定义报错,基础写法参考:
interface IComponentProps { title: string; count?: number; // 非必传属性加?标注,避免必传校验报错 } const MyComponent: React.FC<IComponentProps> = (props) => { // 此处调用props.title、props.count都不会触发未定义提示 return <div>{props.title}</div> }
- 如果用解构赋值取用props属性,确认解构的属性名在类型定义中存在、拼写无误。
- 如果是给组件传参时触发属性不存在提示,确认传入的属性名和组件定义的props属性名完全匹配,必传属性没有遗漏。
- 如果是二次封装第三方组件,需要用继承/交叉类型合并第三方组件原生props类型和自定义类型,以封装Antd Button为例:
import type { ButtonProps } from 'antd' interface IMyButtonProps extends ButtonProps { customProp: string }
2. 无类型定义的第三方库属性声明方法
通用处理方案
- 临时兼容场景可以直接赋值
any类型,不会阻断TS编译,但会丢失对应属性的类型提示:
interface IProps { somelibrary: any }
- 需要完整类型支持的话,先查有没有社区维护的类型包,绝大多数常用库的类型包都放在
@types/命名空间下,例如lodash没有自带类型时,执行npm i @types/lodash -D安装类型包后,直接引入库导出的类型即可:
import type { SomeLibraryType } from 'somelibrary' interface IProps { somelibrary: SomeLibraryType }
- 没有社区类型包的话,可以自行编写声明文件:在项目根目录新建
typings/index.d.ts文件,声明对应模块的类型:
declare module 'somelibrary' { export interface SomeLibraryType { // 按实际用到的属性、方法声明类型即可 init: () => void version: string } const somelibrary: SomeLibraryType export default somelibrary }
编写完成后就可以正常导入类型使用。
i18n属性类型声明示例
如果用的是主流i18n库例如i18next,直接安装对应的类型包@types/i18next,引入i18n实例的类型即可:
import type { i18n } from 'i18next' interface IProps { i18n: i18n }
如果是自行封装的i18n工具,提取封装的i18n对象的类型声明即可,临时兼容也可以先写any或者Record<string, any>过渡。
内容的提问来源于stack exchange,提问作者Витязи Team
相关产品推荐
相关产品推荐

