New TypeScript user. I am converting a RN project to TypeScript. Using hooks all around. I've defined a component BitInput (which forwards a ref to TextInput) as follows:
export interface Props { value: number; onChange?: (newValue: number) => void;}const BitInput: React.FC<Props> = forwardRef( ({ value, onChange }, ref: React.Ref<TextInput>) => { return (<TextInput ref={ref} onChange={onChange} /> );};
I'm using this component to build a ByteInput component as follows:
import BitInput from './BitInput';const BinaryInput: React.FC<Props> = ({ value, onChange }) => { const ref: React.MutableRefObject<typeof BitInput | undefined>[] = [...Array(8)].map(() => useRef<typeof BitInput>() ); const handleKeyPress = (event) => { switch (event.key) { case 'ArrowRight': for (let i = 0; i < ref.length; i++) { if (ref[i].current?.isFocused() && i < ref.length - 1) { ref[i + 1].current.focus(); break; } } break; } }; render() { return (<View><BitInput ref={ref[refIndex++]} onKeyPress={handleKeyPress} /></View> ..... 7 more BitInputs here ..... ); }
I am getting TS2339: Property 'isFocused' does not exist on type 'FC '.
I'm also getting:
TS2322: Type 'MutableRefObject<FC<Props>>' is not assignable to type 'Ref<TextInput>'. Type 'MutableRefObject<FC<Props>>' is not assignable to type 'RefObject<TextInput>'. Types of property 'current' are incompatible. Type 'FunctionComponent<Props>' is missing the following properties from type 'TextInput': isFocused, clear, measure, measureInWindow, and 19 more. BitInput.tsx(11, 3): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'
I can fix both, by using BitInput
instead of typeof BitInput
in the ref declaration. But now I'm getting TS2749: 'BitInput' refers to a value, but is being used as a type here
on it, and on the JSX for BitCode I got the TS error that a lot of the required props are missing.
I'm guessing I'm not specifying the export interface correctly, but what is the proper way?