Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactElement type casting

This is more of a Typescript and React question but for full disclosure, I'll mention that I ended up here while trying to create a custom header using react-navigation.

I have a simple ImageButton (functional) component, which accepts the following props:

export interface ImageButtonProps extends TouchableOpacityProps {
  transparent?: boolean;
}

My custom header looks (roughly) like this:

export default function Header(props: StackHeaderProps) {
   const options = props.scene.descriptor.options;

   const HeaderRight = options.headerRight as (() => ReactElement<ImageButtonProps>);

   return (<HeaderRight transparent={true}/>); // <-- Typescript complains here
}

It's safe to assume that options.headerRight will always return an ImageButton, which in fact renders just fine. The only issue is that the property transparent is always undefined and also Typescript throws the following error:

TS2322: Type '{ transparent: boolean; }' is not assignable to type 'IntrinsicAttributes'.   Property 'transparent' does not exist on type 'IntrinsicAttributes'.

So my question is, how can I properly cast a ReactElement to my custom component, ImageButton and its props?

like image 300
Georgios Avatar asked Sep 02 '25 15:09

Georgios


1 Answers

Your error is because the type you casted it to doesn't take any arguments or props.

This means, a function which takes no arguments, returns React.Element:

() => ReactElement<ImageButtonProps>

You want it to take the props, so you need to type in the props:

(props: ImageButtonProps) => ReactElement<any>

Or

React.ComponentType<ImageButtonProps>

Also, TypeScript doesn't support typechecking ReactElement, so there's no need for doing ReactElement<ImageButtonProps>.

Also see https://reactjs.org/blog/2015/12/18/react-components-elements-and-instances.html

like image 91
satya164 Avatar answered Sep 05 '25 05:09

satya164