#createParamDecorator return type safety

1 messages · Page 1 of 1 (latest)

stone monolith
#

lets say i have created this decorator which is in the docs

  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user;
  },
);```

and i want to call it for example in this controller

@Controller('posts')
export class PostController {
@UseGuards(JwtGuard)
@Get('
getAllPosts(
//decorator call
@GetUser() user // this is any) {
return {data};
}
}

is it possible for the user type to be inferred from the decorator?
I can set it in the controller to any type i want which is not type safe
high dew
#

nop

#

there is no such thing as type inference for parameters decorators in typescript

#

but I like to follow this convention:

foo(@GetUser() user: GetUser) {}

ie., create a type with the same name of the decorator factory

stone monolith
#

I meant like the returned object is known and should be applied to the variable

#

i guess it's a typescript limitation

#

thank you

high dew
#

yes, it is

cinder needleBOT
#

This post has been marked as resolved. :white_check_mark:
Please read through the conversation and resolution if you are having the same issue, and then re-open the post if you are still having trouble, providing as much extra information as possible.

sturdy edge
#

@high dew 🇧🇷 does GetUser needs to a class ?

i dont this typescript type or interface can work in parameters

high dew
#

Sorry, I didnt understand your question

sturdy edge
#
  @Get('getProfile')
  @HttpCode(HttpStatus.OK)
  @UseGuards(AuthGuard, RoleGuard)
  @RoleDecorator([RoleEnum.USER])
  async getProfile(@CurrentUserDecorator() user: UserLeanType): Promise<AppResponseDto> {
    return await this.userService.getProfile(user);
  }

like here UserLeanType is a class, this works

but if i use type or interface it throws error

high dew
#

What is the error? I don’t think that the CurrentUserDecorator requires that but it depends on what the decorator does

sturdy edge
#

export class UserLeanType {
  _id: string;
  firstName: string;
  lastName: string;
  email: string;
  dob: string;
  phoneNumber: string;
  verified: boolean;
  active: boolean;
  role: RoleEnum;
}

i am usign "UserLeanType" to have types for my "user"

#

but if i use interface or typescript type then i get error

#
SyntaxError: The requested module '../../type/userLean.type.js' does not provide an export named 'UserLeanType'
    at ModuleJob._instantiate (node:internal/modules/esm/module_job:228:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:335:5)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:647:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)

this is the error i get when "UserLeanType" is typescript type or interface

but wneh it a class as mentions then it works, no error

high dew
#

Are you using tsc as the builder for nestjs cli? It is the default

sturdy edge
#
{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "deleteOutDir": true,
    "builder": {
      "type": "swc",
      "options": {
        "swcrcPath": "./.swcrc"
      }
    },
    "typeCheck": true
  }
}

i am using swc

high dew
#

Try it out with tsc please

sturdy edge
#

ok

#

will update here

#

@high dew is this an issue or expected result

high dew
#

I didnt use the swc too much tho

#

tsc is fast and reliable enough so far for my projects

sturdy edge
#

apparantly i have set up the code base with ESM focused.

tsconfig.json
{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "lib": ["ESNext"],
    "target": "ESNext",
    "outDir": "./dist",
    "sourceMap": true,
    "noEmit": true,
    "removeComments": true,
    "checkJs": true,
    "strict": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "esModuleInterop": true,

    "declaration": true,
    "allowSyntheticDefaultImports": true,
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": true,
    "forceConsistentCasingInFileNames": true,
    "noImplicitAny": true,
    "strictBindCallApply": true,
    "noFallthroughCasesInSwitch": true,
    "strictPropertyInitialization": false
  },
  "include": ["src/**/*", "test/**/*"],
  "exclude": ["node_modules", "dist"]
}
swcrc
{
  "$schema": "https://swc.rs/schema.json",
  "sourceMaps": true,
  "minify": false,
  "module": {
    "type": "es6",
    "strict": false,
    "strictMode": true,
    "lazy": false,
    "noInterop": false
  },
  "jsc": {
    "externalHelpers": true,
    "target": "esnext",
    "loose": false,
    "keepClassNames": true,
    "preserveAllComments": false,
    "parser": {
      "syntax": "typescript",
      "tsx": false,
      "decorators": true,
      "dynamicImport": true
    },
    "transform": {
      "legacyDecorator": true,
      "decoratorMetadata": true
    }
  }
}
high dew
#

Yes. This is another thing to have in count. It should not be a problem