#Types for custom decorator in NestJS

21 messages · Page 1 of 1 (latest)

bright crest
#

Hello, I'm new to Typescript and am working on a community project using it. I created a custom decorator for my server endpoints using the NestJS docs as reference, and I can't figure out how to fix these unsafe assignment of any typed value errors. Screenshots included.


export const Author = createParamDecorator<string>(
  (data: string, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const author = request.author;

    return data ? author?.[data] : author;
  }
);```
gilded marten
#
const request: Request = context.switchToHttp().getRequest()
const { author } = request;// little improvement ;)

just make sure you import Requeest from express

bright crest
#

Thank you. I tried that already @gilded marten

#

still have squigglies

gilded marten
# bright crest

yeah you need to make sure typescript known what properties are allowed in the request

//express.d.ts
declare module 'express' {
  interface Request {
    // properties here
  }
}
bright crest
#
  export interface Request {

    author?: import("../author/interfaces/author").Author;
    firebaseUid?: string;
  }
}```
#

Yes, I have it

#

Is it just an import issue then?

gilded marten
#

i dont think you are meant to do it like this...

gilded marten
bright crest
#

That's an author interface that describes an Author document in the database

#

Written by a team member

compact ibex
#

The ternary operator doesn't make sense, you might want to double check that.

#

There's no data variable in the function scope

nocturne dune
#

Just extend the express request type and create a new type out of it.

interface ISuperDuperRequest extends Request {
  author: Author
}

const request = context.switchToHttp().getRequest<ISuperDuperRequest>();
request.author
bold glade
bright crest
#

Thank you all. New to TS and NestJs. What do you think of this:

#

Use this line instead

const request = ctx.switchToHttp().getRequest<{ author: { [key: string]: unknown } }>();

Which will assert that request is the type { author: { [key: string]: unknown } }