Home > Enterprise >  Using exported functions in React typescript
Using exported functions in React typescript

Time:06-02

i have 2 questions. How should i use exported functions and how can i use optional arguments?

I created a component just for functions and i want to call it by importing them to other components.

I'm exporting this function as:

    export const verifyOTP = (
      inputId: string,
      setIsVer: (state: boolean) => void | null,
      setProfile: () => void | null,
      setIsAuth: (state: boolean) => void
    ) => {
      let codeInput = document.getElementById(inputId) as HTMLInputElement;
      if (codeInput.value.length === 6) {
        let confirmationRes = window.confirmationRes;

    confirmationRes
      .confirm(codeInput.value)
      .then((res: any) => {
        setIsVer(true);
        setProfile();
        setIsAuth(true);
      })
      .catch((error: ErrorCallback) => console.log(error));
  }
};

And i'm calling it in an input as:

<input
              type="text"
              id="code"
              onChange={() => verifyOTP('code', null, null, setIsAuth)}
              placeholder="Código"
              disabled={disable}
            ></input>

In this component i just want it to trigger setIsAuth. But in another component i want to use all the 4 arguments.

It's throwing this error at the onChange:

Argument of type 'null' is not assignable to parameter of type '(state: boolean) => void | null'.

CodePudding user response:

It's all about operator precedence:

(state: boolean) => void | null is actually a function that can either return void or null.

You want ((state: boolean) => void) | null instead, which is a function that returns void, or just the value null.

  • Related