Typing Middleware JWT and others
Currently I am trying to type the
c.get('jwtPayload')
that is documented here. I have tried using the method described here in a global.d.ts
file but this does not seem to take any affect, the jwtPayload get result is still typed as any.
Currently I have removed the global.d.ts file and set types on the Hono instance instead so its more explicit. This is still not working for the jwtPayload (and other values I use in middelware like the oauth middleware):
13 Replies
@Nico here is the thread, thanks!
I see, to confirm it works fine it’s just the types that are throwing errors
Let me test what you have put here and see for myself and I’ll get back to you
The types are not throwing errors this way, they are just not being inferred. If I check the type of id from the jwtPayload its type is any
And using
as CustomType
does not work correct?as CustomType will work because I am casting the result but this isn't exactly type safe because if the type changes or is unexpexted this won't catch it or give any errors.
it also requires anywhere in the code that c.get() is used for the developer to know what type they should be expecting as there will be no inference
I totally get that, I'm getting on my computer now to check
Have you tried just adding the JWTPayload to the variables
For example this is type safe for me
Yes this works
But the middelware JWT plugin sets a variable called jwtPayload
not jwt
https://hono.dev/middleware/builtin/jwt#usage
Its only an issue when you are trying to type variables in existing middleware
I see what you mean now
The docs here seem to indicate there is a way to do this though - https://hono.dev/api/context#contextvariablemap
That would be for adding, you won't be able to override them. I think for now casting is the only way to achieve this. I will bring up on GitHub for implementing this so maybe you can do
jwt<MyPayload>({})
But it would have to be a way where breaking changes are not implementedYeah I think this would make sense. And if you don’t pass the generic then it just stays as any, that shouldn’t be breaking?
Or the other option is to get rid of the type it sets. I just testing and built that and it just requires people to set the type