I am trying to type a Component prop that could accept both:
JavaScript
x
2
1
const MyInput = RN.TextInput
2
As well as something more custom:
JavaScript
1
5
1
const MyInput = React.forwardRef<RN.TextInput, RN.TextInputProps>(textProps: RN.TextInputProps) =>
2
<RN.View>
3
<RN.TextInput {props} />
4
</RN.View>
5
So, I tried:
JavaScript
1
4
1
const MyComp = (props: {
2
MyInput: React.ComponentType<RN.TextInputProps>
3
}) =>
4
But when trying to set a ref, I get:
JavaScript
1
10
10
1
const MyComp = ({ MyInput }) => {
2
const ref = React.useRef<InputText>()
3
return <MyInput ref={ref}
4
}
5
6
/*
7
Type '{ ref: RefObject<TextInput>; style: { height: number; fontSize: number; lineHeight: number; }; selectTextOnFocus: true; value: string; onChangeText: (text: string) => void; multiline: true; onKeyPress: (e: NativeSyntheticEvent<...>) => void; onSubmitEditing: () => void; onCancelEditing: () => void; }' is not assignable to type 'IntrinsicAttributes & TextInputProps & { children?: ReactNode; }'.
8
Property 'ref' does not exist on type 'IntrinsicAttributes & TextInputProps & { children?: ReactNode; }'.ts(2322)
9
*/
10
Then I tried:
JavaScript
1
6
1
const MyComp = (props: {
2
MyInput: React.ForwardRefExoticComponent<
3
RN.TextInputProps & React.RefAttributes<RN.TextInput>
4
>
5
}) =>
6
But in this case, when trying to pass RN.TextInput
as prop, I get:
JavaScript
1
5
1
<MyComp MyInput={RN.TextInput} />
2
/*
3
Property '$$typeof' is missing in type 'typeof TextInput' but required in type 'ForwardRefExoticComponent<TextInputProps & RefAttributes<TextInput>>'.ts(2741)
4
*/
5
Here is a sandbox showing the issue
Advertisement
Answer
Adding typeof TextInput
solve the TS error for me
JavaScript
1
6
1
const MyComp = (props: {
2
MyInput: React.ForwardRefExoticComponent<
3
RN.TextInputProps & React.RefAttributes<RN.TextInput>
4
> | typeof TextInput
5
}) =>
6
I think you don’t even need the exotic type because TextInput itself already is capable of receiving a ref
JavaScript
1
4
1
const MyComp = (props: {
2
MyInput: typeof TextInput
3
}) =>
4