Home > Back-end >  How to assign TypeScript type to function for parameters?
How to assign TypeScript type to function for parameters?

Time:01-16

I have defined a function and used TypeScript to assign types to the parameters:

const handleLogin = async (
    e: React.FormEvent<EventTarget>,
    navigate: NavigateFunction,
    link: string,
    data: LoginDataType,
    setError: React.Dispatch<React.SetStateAction<string>>,
    setLoading: React.Dispatch<React.SetStateAction<boolean>>
) => {
 
    //function code
  
}

Right now I have provided individual types to the params but I want to create a TypeScript type like:

export type HandleLoginParamTypes = {
    e: React.FormEvent<EventTarget>;
    navigate: NavigateFunction;
    link: string;
    data: LoginDataType;
    setError: React.Dispatch<React.SetStateAction<string>>;
    setLoading: React.Dispatch<React.SetStateAction<boolean>>;
};

Now I want to assign the above type to the function so that in the function definition I do not have to assign types to params individually. Is that possible?

I added the answer provided to my code: My function looks like:

const handleLogin = async (
    {e,navigate, link,data,setError,setLoading}: HandleLoginParamTypes
) => {

    //function code

}

But now when I try to invoke this function as

 handleLogin(e, navigate, "/login", { emailId, password }, setError, setLoading)

I am getting typescript error as

TS2554: Expected 1 arguments, but got 6.

I don't know why the function asks for only one argument.

CodePudding user response:

You can use a type to describe:

  • One parameter.
  • The whole function (i.e. all its parameters and its return value).

e.g.

type param1 = { foo: number };
type param2 = { bar: number };

const example = (first: param1, second: param2) => first.foo   second.bar;

or

type ExampleFunction = (a: number, b: string) => string;
const example: ExampleFunction = (first: number, second: string) => first   second;

You can't describe just multiple parameters in a single type.

You could change the function so it takes one parameter which is an object:

type  = { first: number; second: string; }
const example = ({first, second}: ExampleFunctionParams) => first   second;

CodePudding user response:

You'd have to take one parameter which is an object. So this should work and this is how it's usually done:

export type HandleLoginParamTypes = {
    e: React.FormEvent<EventTarget>;
    navigate: NavigateFunction;
    link: string;
    data: LoginDataType;
    setError: React.Dispatch<React.SetStateAction<string>>;
    setLoading: React.Dispatch<React.SetStateAction<boolean>>;
};

const handleLogin = async ({e, navigate, link, data, setError, setLoading}: HandleLoginParamTypes) => {
 
    //function code
  
}

Like this you also have the benefit of named parameters:

await handleLogin({
  e: //...,
  navigate: //...,
  link: //...,
  data: //...,
  setError: //...,
  setLoading: //...,
});
  • Related