typescript 如何描述在React组件中部分使用的 prop 类型

fhity93d  于 2023-02-10  发布在  TypeScript
关注(0)|答案(1)|浏览(127)

我的React组件获取props并使用from部分,同时将它们进一步放入另一个子组件

<MyComponent prop1="string" prop2="string" prop3="string" prop4="string" /> [3]

type PropsType = {
prop1: string;
prop2: string;
prop3: string; [1]
prop4: string;[2]
}

function MyComponent(props: PropsType) {
const{prop1, prop2} = props;
return(
  <ChildComponent {...props}>
 )
}

type ChildComponentPropTypes = {
prop3: string;
prop4: string;
}

function ChildComponent(props: ChildComponentPropTypes){
const {prop3, prop4} = props;
return(something)
}

我得到一个打字错误:“props 3,props 4”PropType已定义,但从未使用过prop lintreact/no-unused-prop-types请告诉我如何消除此错误
也许你可以决定改变代码的架构来解决这个问题。但是我不想那样做。
如果省略[1]和[2],则会在[3]中得到错误:属性“prop 3,prop 4”在“IntrinsicAttributes & PropsType”类型中不存在

yuvru6vn

yuvru6vn1#

产生错误的是eslint react/no-unused-prop-types规则,而不是Typescript。请尝试在eslint配置中禁用该规则或添加eslint-disable-next-line注解。

function MyComponent(props: PropsType) {
  const{prop1, prop2} = props;
  return(
    // eslint-disable-next-line react/no-unused-prop-types
    <ChildComponent {...props}>
  )
}

相关问题