道具注入HOC和打字稿-如何正确打字?

时间:2020-05-21 03:42:34

标签: reactjs typescript higher-order-components

我正在尝试在Typescript 3.8.3上正确键入道具注入HOC。我以为我记得它是如何工作的,并且像https://stackoverflow.com/a/51084259这样的答案表明这曾经是这种方式,但是在3.8.3中可能不再是这种情况了?

给我的印象是,用来注入HoC的道具的模板是:

interface AddedProps {
  addedProp1: number;
  addedProp2: string;
}

const withProps = <P extends AddedProps>(
  Component: React.ComponentType<P>
): React.FunctionComponent<Omit<P, keyof AddedProps>> => (
  props: Omit<P, keyof AddedProps>
) => <Component {...props as P} addedProp1={1} addedProp2="two" />;

但是当前这会导致在调用位置出现奇怪的打字稿错误:

Argument of type '({ prop, addedProp1, addedProp2 }: Props) => JSX.Element' is not assignable to parameter of type 'ComponentType<AddedProps>'.
  Type '({ prop, addedProp1, addedProp2 }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<AddedProps>'.ts(2345)

Type '{ prop: number; }' is not assignable to type 'IntrinsicAttributes & Pick<AddedProps, never> & { children?: ReactNode; }'.
  Property 'prop' does not exist on type 'IntrinsicAttributes & Pick<AddedProps, never> & { children?: ReactNode; }'.ts(2322)

我在这里有一个MCVE:https://codesandbox.io/s/vibrant-meadow-28wxx-有人能让我知道我在想什么吗?您可以在App.tsx和Note.tsx中看到TSC错误

0 个答案:

没有答案