React TypeScript高阶组件定义

时间:2019-06-13 07:27:44

标签: reactjs typescript typescript-typings higher-order-components

我有一个HOC,它将isLoadingsetLoading添加到包装的组件中,其实现方式与react-navigation withNavigation HOC类似。但是TypeScript抱怨一些类型兼容性错误。

代码如下:

interface State {
    isLoading: boolean;
}

export interface PageLoadingInjectedProps {
    isLoading: boolean;
    setLoading: (isLoading: boolean) => void;
}

interface Args {
    defaultLoading: boolean;
}
export default function withPageLoading<T extends PageLoadingInjectedProps>(PageView: ComponentType<T>, { defaultLoading }: Args = { defaultLoading: true }) {
    type OriginProps = Omit<T, keyof PageLoadingInjectedProps>;
    const WithPageLoading: ComponentClass<OriginProps> = class extends Component<OriginProps> {
        state: State = {
            isLoading: defaultLoading,
        };

        setLoading = (isLoading: boolean) => {
            this.setState({
                isLoading,
            });
        };

        render() {
            return (
                <>
                    <PageView {...this.props} isLoading={this.state.isLoading} setLoading={this.setLoading} />
                    { this.state.isLoading && <LoadingLayer visible={this.state.isLoading} /> }
                </>
            );
        }
    };

    hoistNonReactStatics(WithPageLoading, PageView);

    WithPageLoading.displayName = `withPageLoading(${utils.util.getComponentDisplayName(PageView)})`;

    return WithPageLoading;
}

TypeScript错误是:

Error:(46, 22) TS2322: Type 'Readonly<Pick<T, Exclude<keyof T, "isLoading" | "setLoading">>> & { isLoading: boolean; setLoading: (isLoading: boolean) => void; children?: ReactNode; }' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
  Type 'Readonly<Pick<T, Exclude<keyof T, "isLoading" | "setLoading">>> & { isLoading: boolean; setLoading: (isLoading: boolean) => void; children?: ReactNode; }' is not assignable to type 'T'.

但是withNavigation中的react-navigation定义是相同的:

export function withNavigation<P extends NavigationInjectedProps>(
  Component: React.ComponentType<P>,
): React.ComponentType<Omit<P, keyof NavigationInjectedProps>>;

那么,我的定义怎么了?

0 个答案:

没有答案