【发布时间】:2021-01-31 14:11:59
【问题描述】:
打字稿 - v3.9.7
我有一个向组件传递额外道具的 HOC:
import React from 'react';
interface IWithOwner {
owner: string;
}
type IWithoutOwner<T extends IWithOwner> = Omit<T, keyof IWithOwner> & {owner?: never};
// CORRECT
export function withOwnerOne<TProps extends IWithOwner>(Component: React.ComponentType<TProps>) {
const ComponentWithOwner: React.FunctionComponent<IWithoutOwner<TProps>> = (props) => {
return (
<Component
owner="Tom"
{...props}
/>
);
}
return ComponentWithOwner;
}
// ERROR
export function withOwnerTwo<TProps extends IWithOwner>(Component: React.ComponentType<TProps>) {
return class extends React.Component<IWithoutOwner<TProps>> {
render() {
return (
// '{ owner: string; } & Readonly<IWithoutOwner<TProps>> & Readonly<{ children?: ReactNode; }>'
// is assignable to the constraint of type 'TProps', but 'TProps' could be
// instantiated with a different subtype of constraint 'IWithOwner'.
<Component
owner="Tom"
{...this.props}
/>
)
}
}
}
withOwnerOne 使用 Function 组件可以正常工作。而使用类组件的withOwnerTwo 有错误。为什么它们的工作方式不同?
【问题讨论】:
-
对我来说这两种情况都失败了
-
@Drag13 也许这取决于打字稿版本或其他东西。你看过游乐场链接吗?
-
它在操场上,在我更改了一些符号并撤消更改后
标签: reactjs typescript higher-order-components react-typescript