使用TypeScript反应HOC错误

时间:2018-07-16 13:24:46

标签: reactjs typescript higher-order-components

我正在尝试创建一个包装函数,以使React上下文使用者成为用TypeScript编写的HOC。这是我到目前为止的内容:

import { ComponentType, ConsumerProps, createElement } from 'react';

type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;

export const createConsumer = <S>(
  consumer: ComponentType<ConsumerProps<S>>
) => <P>(
  component: ComponentType<P & S>
) => (
  props: Omit<P, keyof S>
) => createElement(consumer, {
  children: (state: S) => createElement(component, {
    ...props as any,
    ...state as any
  })
});

除了嵌套HOC之外,其他所有方法都可以正常工作。当我这样做时,它只会拾取上一个HOC的道具,而忽略其他所有道具。

import * as React from 'react';
import { createContext } from 'react';

import { createConsumer } from './createConsumer';

const firstContext = createContext({ first: 'value' });
const withFirst = createConsumer(firstContext.Consumer);

const secondContext = createContext({ second: 'value' });
const withSecond = createConsumer(secondContext.Consumer);

const Component = withFirst(withSecond(({ first, second }) => (
//                                        ^^^^^
// TS2459: Type '{ second: string; } & { children?: ReactNode; }' has no property 'first' and no string index signature.
  <div/>
)));

有人知道是什么问题吗?

0 个答案:

没有答案