ミドルウェアで次のようにユーザー情報をいれようとしました。
app.use((req, res, next) => {
req.user = hogehoge;
});
怒られました。
Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'
いろいろ調べた結果、globalにExpressのrequestを拡張すればよいことがわかりました。
https://stackoverflow.com/questions/37377731/extend-express-request-object-using-typescript/58788706
やり方
@types/express/index.d.ts
というフォルダとファイルを作る。
名前は必ずこれである必要あり。フォルダの場所はアプリルートでも、srcフォルダ以下でもよい。
// req.user が使えるようにする。
declare namespace Express {
export interface Request {
user: any;
}
}
tsconfig.jsonを編集する
typeRootsを追加。自分で先程追加した@typesの場所とnode_modules/@types
を追加。この場合はsrc/以下に作ったのでsrc/@typesとなっている。
"compilerOptions": {
"typeRoots": ["src/@types", "node_modules/@types"],
...
}
これでうまくいきました。