Reactjs 无法键入HOC以添加默认道具

Reactjs 无法键入HOC以添加默认道具,reactjs,typescript,Reactjs,Typescript,我想创建一个高阶组件,向组件添加默认道具。这些默认道具可以被覆盖 下面是我想要实现的一个例子: type VehicleProps = { wheels: number; brand: string; }; const Vehicle:React.FC<Vehicle> = props => ... const Car = setDefaultProps(Vehicle)({wheels:4}) // Car should have type React.FC<

我想创建一个高阶组件,向组件添加默认道具。这些默认道具可以被覆盖

下面是我想要实现的一个例子:

type VehicleProps = {
  wheels: number;
  brand: string;
};

const Vehicle:React.FC<Vehicle> = props => ...

const Car = setDefaultProps(Vehicle)({wheels:4})
// Car should have type React.FC<{brand:string, wheels?:number}> with wheels defaulting to 4
type VehicleProps={
轮子:数量;
品牌:弦;
};
const Vehicle:React.FC=props=>。。。
const Car=setDefaultProps(车辆)({wheels:4})
//汽车应具有React.FC类型,车轮默认为4
道具

我得到了错误

“Props”可以用任意类型实例化,该类型可以是 与'Pick&{[K in K]+?:Props[K]| undefined;}无关& 省略'

我错过了什么?

您可以尝试以下方法:

const wheelHOC = (wheel) => WrappedComponent => () => {

  return <WrappedComponent
    wheel={ wheel | 4 }/>;
};

const Component = (props) => {
  return <div>I have { props.wheel } wheels</div>
}

const WheelsDefault = wheelHOC()(Component)
const WheelsCustom = wheelHOC(5)(Component)

export default function App() {
  return (
    <div className="App">
      <WheelsDefault/>
      <WheelsCustom/>
    </div>
  );
}
constwheelhoc=(wheel)=>WrappedComponent=>()=>{
返回;
};
常量组件=(道具)=>{
return我有{props.wheel}个轮子
}
const WheelsDefault=wheelHOC()(组件)
常量WheelsCustom=wheelHOC(5)(部件)
导出默认函数App(){
返回(
);
}

为什么不这样使用解构:
const Component=({wheel=4})=>轮子数量:{wheel}
?在HOCs中重新组合道具会经常出现此错误。有时我可以看到它的边缘情况,它实际上与类型不匹配。但是您是基于键
K
的,因此没有缩小值的机会。我可以得到一个错误
类型“Pick&ommit”不可分配给类型“Props”。
对此我有些挠头。在函数内部声明类型
DefaultProps
FinalProps
似乎很奇怪,尽管它似乎确实起作用。您不需要
typeofdefaultprops
,因为您已经知道变量的类型是
Pick
。您只需执行
return(props:Partial&ommit)=>
简单的解决方案是断言:
return(props:Partial&ommit)=>但我很想知道如何避免这种情况!这是一个关于Typescript错误的问题,您的代码没有任何Typescript类型。