【发布时间】:2021-10-05 05:00:56
【问题描述】:
我有一个 HOC 函数,它接受一个组件和一个属性键,并返回具有在指定属性键处注入的值的组件。这是我的概念证明:
import * as React from 'react'
type WrappedComponentProps<PropertyKey extends string> = {
[k in PropertyKey]: boolean
}
type WithCustomPropertyProps<P, PropertyKey extends string> = Omit<P, PropertyKey> & P
const withCustomProperty = <
PropertyKey extends string,
P extends WrappedComponentProps<PropertyKey>,
CurrWithCustomPropertyProps = WithCustomPropertyProps<P, PropertyKey>
>(propertyName: PropertyKey) => {
return (WrappedComponent: React.ComponentType<P>): React.FC<CurrWithCustomPropertyProps> => {
const WithMediaQuery: React.FC<CurrWithCustomPropertyProps> = (props: CurrWithCustomPropertyProps) => {
return <WrappedComponent {...props} {...{ [propertyName]: true }} />
}
return WithMediaQuery
}
}
type Props = {
anotherProperty: string
} & WrappedComponentProps<'propertyKey'>
class Test extends React.Component<Props> {
render() {
return <div></div>
}
}
const _test = withCustomProperty('propertyKey')(
Test
)
但是,正如您在 TypeScript Playground 中看到的,我收到两个错误:
Type 'CurrWithCustomPropertyProps & { [x: string]: boolean; }' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
Type 'CurrWithCustomPropertyProps & { [x: string]: boolean; }' is not assignable to type 'P'.
'P' could be instantiated with an arbitrary type which could be unrelated to 'CurrWithCustomPropertyProps & { [x: string]: boolean; }'.
Argument of type 'typeof Test' is not assignable to parameter of type 'ComponentType<WrappedComponentProps<"propertyKey">>'.
Type 'typeof Test' is not assignable to type 'ComponentClass<WrappedComponentProps<"propertyKey">, any>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'WrappedComponentProps<"propertyKey">' is not assignable to type 'TestProps | Readonly<TestProps>'.
Property 'anotherProperty' is missing in type 'WrappedComponentProps<"propertyKey">' but required in type 'Readonly<TestProps>'.
我承认我对这里发生的事情没有任何线索。以上是我尝试过的替代方案之一,我尝试了其他几个,但没有任何改进。
我想我应该将 HOC 函数返回的组件的组件道具与包装组件的道具链接,但我不知道如何。有什么想法吗?
【问题讨论】:
-
太忙无法回答,但我几天前回答了一个类似的问题,可能会有所启发:stackoverflow.com/questions/68511373
标签: reactjs typescript typescript-typings