NestJS tip: type safety on parameter decorators
Tags: nestjs, node, programming, typescript
Published: 2023-05-20 16:52:14

> for NestJS v8, v9 and v10

In NestJS we can create specialized kind of parameters decorators using the [`createParamDecorator`](https://docs.nestjs.com/custom-decorators) function from `@nestjs/common`. For example:

```ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common'

export const CurrentUser = createParamDecorator<
  keyof User | undefined, // the type of `data`
  ExecutionContext, // the type of `ctx`
>(
  (data, ctx) => {
    const request = ctx.switchToHttp().getRequest()
    const user = request.user
    return typeof data === 'undefined'
      ? user[data]
      : user
  }
)
```

And then you can use that `CurrentUser` parameter decorator later in controller class's method, as follows:

```ts
// ...
@Get()
getCurrentUser(
  @CurrentUser() user: User,
  @CurrentUser('name') username: string,
) {
  return { user, username }
}
```

### The issue

If your project has a bunch of those decorators, it might be hard to know what would be the type of their resolved values, right? I mean, how do you know that `@CurrentUser()` is a "bind" for `request.user` without some documentation or by reading the source? Also, what is the type of that `request.user`? Due to how TypeScript legacy decorators works, there's no way to typescript compiler infer some type from such param decorator.

### My solution

You could see in [my other article](https://dev.to/micalevisk/nestjs-tip-platform-agnostic-way-to-define-response-statusheaders-500o) that I've leverage on TypeScript [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) feature like this:

![basic demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ce9tx0et36qof03bn6xt.png)

Along with [generics](https://www.typescriptlang.org/docs/handbook/2/generics.html), we can now easily couple the decorator with "its" type.

We just need to declare and export a type alias with the same name of our param decorator. See:

```ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common'

export const CurrentUser = createParamDecorator<
  keyof User | undefined, // the type of `data`
  ExecutionContext, // the type of `ctx`
>(
  (data, ctx) => {
    const request = ctx.switchToHttp().getRequest()
    const user = request.user
    return typeof data === 'undefined'
      ? user[data]
      : user
  }
)

// -------- THIS IS NEW:
export type CurrentUser<Prop extends keyof User | undefined = undefined> =
  Prop extends keyof User ? User[Prop] : User
```

```ts
@Get()
getCurrentUser(
  @CurrentUser() user: CurrentUser,
  @CurrentUser('name') username: CurrentUser<'name'>
) {
  return { user, username }
}
```


### Advantages

The ones I've seen so far:

1. No one needs to recall what is the expected type of the resolved value by those parameters decorators. Just use the same name of the decorator.
2. One source of truth of the expected type of such param decorator. If we change the implementation of that decorator in the future (and also the type of the returned object), we won't have to touch other parts of our codebase _(unless we got some breaking change, of course)_.
3. No need to import multiple types just for the sake of type safety.

### Disadvantages

The ones I've seen so far:

1. I didn't see this pattern often in the wild, so I won't expect it to be intuitive.
2. If you use some pipe like this: `@CurrentUser(MyPipe) somethingElse: any`, that `somethingElse` parameter  might not have the `CurrentUser` type anymore. So this pattern is restrict to those decorators that are not meant to use with pipes.
3. `User` type is clear than `CurrentUser` one if you are familiar with `User` entity already. Thus, by reading the code outside of some code editor, it migth be a bit hard to find what that `CurrentUser` mean. But I think that this is just a matter of getting used of.