Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

typescript - 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.

question from:https://stackoverflow.com/questions/65831842/type-text-string-void-is-not-assignable-to-type-void

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...