Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make ParameterDecorator and the like generic #42528

Open
entropitor opened this issue Jan 28, 2021 · 2 comments
Open

Make ParameterDecorator and the like generic #42528

entropitor opened this issue Jan 28, 2021 · 2 comments
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@entropitor
Copy link

lib Update Request

Missing / Incorrect Definition

ParameterDecorator is currently not generic, it can be attachted to any parameter. However, when a decorator is used for e.g. Dependency Injection purposes, some decorators require the type of the parameter to be consistent with the type of the decorator

Sample Code

E.g. we want this to work

class MyController {
  requestThings(@UserId() userId: number): Thing[] { return [] }
}

But this to fail:

class MyController {
  requestThings(@UserId() userId: string): Thing[] { return [] }
}

(as userId will be a number, not a string so the injection should ideally not be possible (at compile time)

Currently UserId is done more or less this way:

const UserId = (): ParameterDecorator => (target, key, index) => { 
  // do stuff
}

while I'd like to add number to ParameterDecorator:

const UserId = (): ParameterDecorator<number> => (target, key, index) => { 
  // do stuff
}

and I'd like typescript to check this when applying a decorator.

@RyanCavanaugh RyanCavanaugh added Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript labels Jan 30, 2021
@gastonmorixe
Copy link

This is really important, specially in NestJS where decorators are used broadly. I'd love to know event have to specify the type at all in the param.

https://docs.nestjs.com/custom-decorators#param-decorators

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

export const User = createParamDecorator<unknown, ExecutionContext, UserEntity>(
  (data: unknown, ctx) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user;
  },
);
@Get()
async findOne(@User() user) { // user should automatically be typed as UserEntity
  console.log(user);
}

@ianzone
Copy link

ianzone commented May 3, 2024

Mark nestjs/nest#11414

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

4 participants