Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6290

Specify exact type of functional component as prop in React Native

$
0
0

I want to achieve a simple (?) task. I want to create my custom functional component that accepts two components as params: a Text and a Button. I need that exactly those types are passed, so if I'll pass a View it should not work.

I tried with:

interface SampleArgs {  text: ReactElement<TextProps>;  button: ReactElement<ButtonProps>;}const Sample = ({ text, button }: SampleArgs) => {  return (<View><Text>Hello world!</Text>      {text}      {button}</View>  );};export { Sample };

But when I'm trying to use it inside my App.tsx every component is accepted without any complains:

{/* No warnings/error, ok! */}<Sample  text={<Text>I should work!</Text>}  button={<Button title={'I should work'}/>}/>{/* No warnings/error, hey, it shouldn't work! */}<Sample  text={<View><Text>Passed View instead of Text, I shouldn't work!</Text></View>  }  button={<Text>Passed Text instead of Button, I shouldn't work!</Text>}/>

Specifying in the interface text: Text; works, but then I cannot use text={<Text>I should work!</Text>} anymore because Type 'Element' is not assignable to type 'Text'.

Specifying in the interface text: ReactElement<Text>; works, but any element is accepted anyway.

Yes, functional components are required, we don't use class ones anymore.

Is there a way to achieve this and restrict types of component?


Viewing all articles
Browse latest Browse all 6290

Trending Articles