Open2
TypeScriptのちょっとしたTips

Expressのrouterのハンドラー関数でasyn/awaitをつけるとESLintのエラーになる
事象
30:25 error Promise returned in function argument where a void return was expected @typescript-eslint/no-misused-promises
解決方法
RequestHandler
で型アサーション(Type Assertion)をする。
router.post('/hoge', (async (req: Request, res: Response) => {
...
}) as RequestHandler);

Record<string, (options: { app: express.Application; }) => void>の関数を呼び出そうとしてコンパイルエラー
事象
Object.keys(routes).forEach((route: string) => {
routes[route]({ app });
});
srv/app.ts:14:2 - error TS2722: Cannot invoke an object which is possibly 'undefined'.
14 routes[route]({ app });
解決方法
undefined
にならないことを保証するように実装する。
※もっといい実装があるかもしれない…。
Object.keys(routes).forEach((route: string) => {
const routeResister = routes[route];
if (routeResister && typeof routeResister === 'function') routeResister({ app });
});