I find myself in a state of confusion regarding Typescript and its suggestions for type definitions. Currently, I am working on a Graphql API with Apollo Server and attempting to implement authorization using JWT via request headers (I am rewriting an existing API). To start, I am extracting the token from request headers like this:
const token: string = req.headers.authorization
However, this results in an error stating "type string | undefined is not assignable to type string", so I adjusted it to:
const token: string | undefined = req.headers.authorization
After making this change, I noticed that the original API attempts to retrieve the authorization property from either req.headers.authorization
or req.headers.Authorization
. Although I do not understand why, I decided to follow suit by trying:
const token: string | undefined = req.headers.authorization || req.headers.Authorization
This led to a new error message: "type string | string[] | undefined is not assignable to type string | undefined".
So, I made another adjustment:
const token: string | undefined | string[] = req.headers.authorization || req.headers.Authorization
Now, I have some questions:
- Why do
req.headers.authorization
andreq.headers.Authorization
have different data types? - After searching online, I see that all tutorials on authorization use
req.headers.authorization
, but what aboutreq.headers.Authorization
?