cloudpg07
cloudpg07

Reputation: 21

Passing an interface type as a parameter to a function

I have an interface like this:

interface IloginReq {
  email: string;
  password: string;
}

and another interface like below:

export interface IReq<T = void> extends e.Request {
  body: T;
}

and I am passing a request to a login function that use both the interfaces as types:

async function login(req: IReq<IloginReq>, res: IRes) {
  const { email, password } = req.body;
  // Add the jwt cookie
  const jwt = await authService.getJwt(email, password);
  const { key, options } = EnvVars.cookieProps;
  res.cookie(key, jwt, options);
  //   Return
  return res.status(HttpStatusCodes.OK).end();
}

Can someone please help me to understand what the meaning of this parameter declaration in login function - req: IReq<IloginReq> - is?

Upvotes: 1

Views: 1524

Answers (1)

FatihAziz
FatihAziz

Reputation: 453

The Basic:

export interface IReq<T = void> extends e.Request {
 body: T;
}

It's called Generic Type (https://www.typescriptlang.org/docs/handbook/2/generics.html#working-with-generic-type-variables). It allows you to pass another Type as Parameter.

You will found it on many places, even built-in utility types also Generic Type

Promise<T>: it's type for anything that asynchronous, so Promise<string> is asynchronous of string

Array<T>: it's type for array, so Array<string | number> is the same as (string | number)[]


Your Code Explanation:

type IReq simply has a body property that has a type of T

So, async function login(req: IReq<IloginReq>, res: IRes) means, req argument is a type of IReq<IloginReq>,

so req.body has a type of IloginReq. Then, req.body.email and req.body.password will be accessible (also for your auto-completion, if using VS Code).

I hope it helps,

Best Regards

Upvotes: 1

Related Questions