0

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Now it says 'Cannot invoke object that's possibly null', so i tried setIsVer && setIsVer(true); and apparently it's working. Is there another better/smarter way to do it?
@JoséCarlos Yes, you can optionally call an expression if it is not null or undefined with setIsVer?.(true). Looks wild, but it's to match optional chaining (foo?.bar).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.