Bjørnar Hvidsten
Bjørnar Hvidsten

Reputation: 969

How to redefine type for React class prop

I´m using Avatar from react-native-elements and the ImageComponent prop is typed as React.ComponentClass (IntelliSense report type React.ComponentClass<{}, any>)

When using a functional component (with prop key) I get red squiggles under 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)

AvatarImage:

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

How can I fix this typescript error?

I´ve tried to define a new class/interface that extend Avatar/AvatarProps:

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

  class MyAvatar extends Avatar<MyAvatarProps> {}

I get typescript error Type 'Avatar' is not generic.ts(2315)

How do I extend Avatar with MyAvatarProps when it's not generic?

Or is there other/better ways to handle this?

Update:

See my answer below

Upvotes: 0

Views: 228

Answers (1)

Bj&#248;rnar Hvidsten
Bj&#248;rnar Hvidsten

Reputation: 969

I got around the issue with a simple TS cast:

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

Upvotes: 1

Related Questions