如何为 React 类 prop 重新定义类型

问题描述

我正在使用 Avatar 中的 react-native-elements,并且 ImageComponent 道具的类型为 React.ComponentClass(IntelliSense 报告类型 React.ComponentClass<{},any>

当使用功能组件(带有 prop 键)时,我在 ImageComponent 下看到红色波浪线:

  <Avatar
    rounded
    size={c.styles.avatarSize}
    containerStyle={{ margin: c.styles.marginLRTB / 2 }}
    placeholderStyle={{ backgroundColor: colors.background }}
    ImageComponent={() => AvatarImage(key)}
  />

Type '() => JSX.Element' is not assignable to type 'ComponentClass<{},any>'.ts(2769)

头像:

  const AvatarImage = (key: string) => (
    <Fastimage
      style={{ width: '100%',height: '100%' }}
      source={sourcesstate[key].category === 'in-app' ? avatars[key as QuotesListKeys] : { uri: sourcesstate[key].imageUrl }}
    />
  );

我该如何修复这个打字稿错误

我尝试定义一个扩展 Avatar/AvatarProps 的新类/接口:

  type MyAvatarProps = Omit<AvatarProps,'ImageComponent'> & { ImageComponent: FC<{ key: string }> };

  class MyAvatar extends Avatar<MyAvatarProps> {}

我收到打字稿错误 Type 'Avatar' is not generic.ts(2315)

如果 Avatar 不是通用的,我如何使用 MyAvatarProps 扩展它?

或者有其他/更好的方法来处理这个问题吗?

更新:

请看下面我的回答

解决方法

我通过一个简单的 TS 转换解决了这个问题:

ImageComponent={((() => AvatarImage(key)) as unknown) as ComponentClass<{},any>}