React组件部分使用Props时的类型定义与ESLint报错解决
解决ESLint与TypeScript的冲突问题
方法一:通过TypeScript类型合并拆分props(推荐)
先定义子组件的props类型,再将父组件自身需要的props与子组件props合并,同时用剩余运算符提取透传的props,既满足TypeScript类型检查,又让ESLint识别到props被透传使用:
// 子组件props类型 type ChildComponentPropTypes = { prop3: string; prop4: string; }; // 父组件props = 自身使用的props + 子组件props type PropsType = { prop1: string; prop2: string; } & ChildComponentPropTypes; function MyComponent(props: PropsType) { // 解构自身需要的props,剩余部分作为子组件props const { prop1, prop2, ...childProps } = props; return <ChildComponent {...childProps} />; } function ChildComponent(props: ChildComponentPropTypes) { const { prop3, prop4 } = props; return <div>{prop3}{prop4}</div>; } // 调用时无TypeScript错误 <MyComponent prop1="string" prop2="string" prop3="string" prop4="string" />;
方法二:临时禁用特定行的ESLint规则
如果不想调整类型结构,可以在未直接使用的props定义上方添加ESLint禁用注释,跳过该规则检查:
type PropsType = { prop1: string; prop2: string; // eslint-disable-next-line react/no-unused-prop-types prop3: string; // eslint-disable-next-line react/no-unused-prop-types prop4: string; }; function MyComponent(props: PropsType) { const { prop1, prop2 } = props; return <ChildComponent {...props} />; }
方法三:调整ESLint规则配置
在ESLint配置文件中,修改react/no-unused-prop-types规则,添加ignoreCustomTypeFields选项,让规则忽略TypeScript类型中用于透传的props:
{ "rules": { "react/no-unused-prop-types": [ "error", { "ignoreCustomTypeFields": true } ] } }
注意:此方法会全局忽略自定义类型中的未使用props,需根据项目情况评估是否适用。
内容的提问来源于stack exchange,提问作者Dmitriy Prigulnov
相关产品推荐
相关产品推荐

