Search code examples
typescriptionic-react

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017) typescript


I'm creating an input handleChange but getting an error Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017) when trying to update the state(this.setState). here is the code snipet

const [first_name, setFname] = useState<string>();
  const [last_name, setLname] = useState<string>();
  const [email, setEmail] = useState<string>();
  const [avatar, setAvatar] = useState();
  
   const handleChange = (e:any) => {
        const { name, value } = e.target;
        this.setState({ [name]: value });
    };


Solution

  • The primary problem is this:

    this.setState({ [name]: value });
    

    That looks like code meant to be in a class component, but you only use hooks in functional components (or other hooks), not class components. With functional components and hooks, you don't use a central setState method, you use the setters you get from useState instead.

    Also, the error message indicates that TypeScript things that code is at global scope, which is odd because again, you don't use hooks there.

    Finally, TypeScript should be complaining about your useState calls, since you've used string as the generic type parameter but haven't provided any initial value. The initial value will default to undefined, which isn't a string.


    It's a bit tangential, but what the error is specifically saying is that the type of this in that code (typeof globalThis) doesn't have a setState property defined on it, so this.setState implicitly has the any type because TypeScript has no type information for it. You're using it as a function, so TypeScript is warning you that it doesn't have anything telling it that this.setState is a function.