Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type '(text: string) => void' is not assignable to type '() => void'

I'm creating a custom component for TextInput. But I've got a problem when I try to pass a function prop to the custom component. This is the code

// Screen.tsx
export const RegisterScreen = ({props}: Props) => {
  const [text, setText] = useState("");
 
  const onChangeInputText = (text: string) => setText(text);

  return (
    <View>
        <CustomInput onChangeText={onChangeInputText} text={text} />
    </View>

// CustomTextInput.tsx
type Props = {
  onChangeText: () => void;
  text?: string;
};

export const CustomInput = ({ onChangeText, text }: Props) => {
  return (
    <TextInput
      style={styles.container}
      onChangeText={onChangeText}
      value={text}
      placeholder="Type here"
    />
  );
};

With this code, I got this error

Type '(text: string) => void' is not assignable to type '() => void'

I think I know what causes this (it's probably on the type declaration?) but since this is actually my first time trying TypeScript, I can't really figure out how to solve this. Tried googling about this first but I didn't find any error similar to mine.

like image 751
arahpanah Avatar asked May 13 '26 22:05

arahpanah


1 Answers

The type definition for this function says "Hey, i need to be passed a string in order to do my job":

const onChangeInputText = (text: string) => setText(text);

But the definition for the onChangeText prop says "I'm not going to pass anything to you":

type Props = {
  onChangeText: () => void;
  text?: string;
};

Your code will actually pass a string through, so you should just need to update the type on the prop.

type Props = {
  onChangeText: (val: string) => void;
  text?: string;
}
like image 62
Nicholas Tower Avatar answered May 16 '26 17:05

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!