Express with Typescript: "Element implicitly has an 'any' type"

Asked

Viewed 341 times

3

I’m trying to dynamically generate my application routes with the Express.router() using Typescript and Node, but it doesn’t work and I’m not able to understand why.

If anyone please knows what is going on give me an explanation about or somewhere I can consult, I did not find anything similar in the documentation =(

router[route.method](route.path, route.handler, route.middleware)

The above code works normally on Node.js but in Typescript the following error occurs:

Element implicitly has an 'any' type because Expression of type 'string' can’t be used to index type 'Router'.
No index Signature with a Parameter of type 'string' was found on type 'Router'.

Playground

1 answer

3


You are getting this message because your code is compiled with the option --noImplicitAny what force the Typescript to trigger an exception in statements and expressions where the type any is implicit.

The express js. is a library written in Javascript, which is a language known to impose no type restrictions. In Typescript is different the language is a superconjunto strongly typified from the Javascript. When you try to index router[route.method], to use routes whose names are invalid in Javascript/Typescript, the Typescript implicitly converts the string route.method in the typo any for the object const router: Router = Express.Router();was written in Javascript which does not have the index signature mechanism in Typescript.

To fix just remove or set the option --noImplicitAny as false.

In the Playground go to Config and disable the option noImplicitAny. inserir a descrição da imagem aqui

Edit:

As stated in the comments another possibility is to keep the option noImplicitAny and force an explicit cast:

routes.map(route =>
    (route.middleware)
    ? (router as any)[route.method](route.path, route.handler, route.middleware)
    : (router as any)[route.method](route.path, route.handler)
)
  • But n has another way, without disabling this option in tsconfig.json ?

  • That option --noImplicitAny is not suitable for connecting libraries JS. Use it when using pure code only on Typescript.

  • 1

    Another option would be to use a cast explicit to any only in router[route.method as any], so it is not necessary to disable the option for the whole project.

  • 1

    @Luizfelipe Tested on the playground continues not supporting.

  • 1

    Really, you should have tested it before commenting, hehe. If you do the cast in the instance of router works: (router as any)[route.method].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.