Strange TS2322 (Type not assignable) Error

Viewed 512

I have a super simple code snippet here, but no matter which editor I use (Webstorm, VSCode) I get red underlines under my SearchBar's "onChangeText" property with the following message:

TS2322: Type '(val: string) => void' is not assignable to type '((text: string) => void) & ((text: string) => void) & (() => any) & (() => any) & (() => any) & ((text: string) => void) & (() => any) & (() => any) & (() => any)'.   Type '(val: string) => void' is not assignable to type '() => any'.

The code is as follows:

import React from "react";
import { useState } from "react";
import { StyleSheet, View } from "react-native";
import { SearchBar } from "react-native-elements";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import ScreenWrapper from "../styled/ScreenWrapper";

const HomeScreen = (): JSX.Element => {
  const [searchString, setSearchString] = useState("");

  function updateSearch(val:string):void {
      setSearchString(val)
  }

  return (
    <ScreenWrapper>
      <KeyboardAwareScrollView
        contentContainerStyle={styles.container}
        resetScrollToCoords={{ x: 0, y: 0 }}
        scrollEnabled={false}
      >
        <SearchBar
          placeholder="Type here to search tournaments"
          onChangeText={updateSearch}
          value={searchString}
        />
      </KeyboardAwareScrollView>
    </ScreenWrapper>
  );
};

The code seems to compile and execute just fine, but the error in the editor is driving me nuts. Is there a good reason that this is showing?

1 Answers

The compiler believes that your updateSearch function might be called in a context that expects () => any, presumably because of typing on the onChangeText attribute. Since your function could be called without any arguments, the compiler thinks it's an error for your function to require any argument. You can fix this by making the val argument optional, such as with a reasonable default:

function updateSearch(val = ""):void {
    setSearchString(val)
}

The documentation for that attribute doesn't clarify the arguments it provides, but the typing appears to be correct in the code itself. Not sure what's going on with the compiler here.

Related