Reactjs typescript 3.6中的默认类型参数和默认参数
自从升级到typescript 3.5以来,我一直被相同的错误消息困扰,我不明白: 我有这个反应组件Reactjs typescript 3.6中的默认类型参数和默认参数,reactjs,typescript,Reactjs,Typescript,自从升级到typescript 3.5以来,我一直被相同的错误消息困扰,我不明白: 我有这个反应组件 export const RouteWrapper = function RouteWrapper< P = { children?: ReactNode }, TRoute extends RouteProps = Route >( Wrapper: React.ComponentType<P>, RouteType: React.ComponentTy
export const RouteWrapper = function RouteWrapper<
P = { children?: ReactNode },
TRoute extends RouteProps = Route
>(
Wrapper: React.ComponentType<P>,
RouteType: React.ComponentType<RouteProps> = Route,
options: Partial<TRoute> = {},
wrapperProps: P = ({} as unknown) as P
) {
return function RouteWrapperResuslt({
component: RouteComponent,
path,
exact,
...rest
}: RouteWrapperProps<P, Partial<TRoute>>) {
return (
<RouteType
path={path}
exact={exact}
{...options}
component={(props: P) => (
<Wrapper {...wrapperProps || {}}>
<RouteComponent {...rest} {...props} />
</Wrapper>
)}
/>
);
};
};
下面是一个完整的示例,因为您传递的是一个空对象,为什么不将其转换为另一个呢??我认为这应该适合你:
Wrapper: React.ComponentType<P | {}>, // Line 23 index.tsx
Wrapper:React.ComponentType,//第23行index.tsx
{}
类型将只允许一个空对象,因此它应该很好地涵盖您的两种情况。错误是不言自明的。如果执行wrapComponentInReduxForTesting()
,则{}
不是道具的有效初始值,并且该值已被标记,因为……….您可能希望将代码转换为。否则,修复方法就是将props
作为可选参数,因为它在函数体中未使用。由于返回类型不依赖于P
,我建议将函数设置为非泛型函数,并将P
替换为unknown
。另外,上面的代码是一个错误,至少可以追溯到2.4。如果您从一个代码没有错误的版本升级,它可能有错误。祝你好运非常感谢。完全没有在泛型类型中使用联合
Type '{ children: Element; }' is not assignable to type 'P'.
'{ children: Element; }' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint '{}'
Wrapper: React.ComponentType<P | {}>, // Line 23 index.tsx