React打字稿类型'FC <{....}>'不满足'FC <{}>'

时间:2020-04-30 19:14:59

标签: reactjs typescript typescript-generics

import * as React from "react";

const Input: React.FC<{ abc: string }> = props => {
  return <input />;
};

const F = <T extends React.FC>(
  props: React.PropsWithChildren<
    { Component: T; a: string; b: boolean; c: object } & Parameters<T>[0]
  >
) => {
  const { Component, a, b, c, ...other } = props as { Component: React.FC<any> };
  return <Component {...other } />;
};

export default function App() {
  return <F Component={Input} abc='123'/>;
}

这是错误消息

Type 'FC<{ required: string; }>' is not assignable to type 'FC<{}>'.
  Types of parameters 'props' and 'props' are incompatible.
    Type '{ children?: ReactNode; }' is not assignable to type 'PropsWithChildren<{ required: string; }>'.
      Property 'required' is missing in type '{ children?: ReactNode; }' but required in type '{ required: string; }'

如果Input元素具有必需的道具(在这种情况下为abc道具),则会发生这种情况

我尝试过的解决方案:

解决方案1:

如果我将<T extends React.FC>更改为<T extends React.FC<any>>,该错误就会消失

由于props,我的any类型更改为& Parameters<T>[0]

我仍然可以通过道具的铸造来解决这个问题

第二个解决方案是我将<T extends React.FC>更改为<T extends typeof Input>

================================================ =============================

我有2个问题

我不喜欢解决方案1,因为我需要进行类型转换,我认为这不是“正确”的实现方式

我认为解决方案2很好,但是如果我将它与更多组件结合起来,例如<T extends typeof Input|typeof Input2>

第一个问题,什么是解决这个问题的正确方法

第二个问题,请帮助我了解为什么会出错?

这是codesandbox(随附上述解决方案)

0 个答案:

没有答案