LoginSignup
6

More than 3 years have passed since last update.

posted at

updated at

Express × TypeScript にてError ['req' is declared but its value is never read.]

ExpressをTypeScriptを用いて書いた時にでたエラーの回避方法について。

初心者向けです。

環境

express :4.17.1
@types/express 4.17.2
typescript: 3.7.2

エラーの内容


import Express from 'express';

const app = Express();

app.get('/', (req, res) => res.send('API Running'));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

上記のような際にapp.getを呼び出した際にreqを呼び出していませんという意味のエラーです。

Unable to compile TypeScript:
'req' is declared but its value  is never read.

コンパイルに失敗します。

(呼び出しているのはresだけ。reqは呼び出されることはない。)

このように、フレームワークの設定上どうしても呼び出さないメソッドが現れることも多くあると思います。
(Expressはreqを記述したあとでないと、resを呼び出すことができない。)

解決法

解決方法は簡単でtsconfig.jsonにて、noUnusedParametersをfalseにしてあげます。

tsconfig.json
{
  "compilerOptions": {
     .
     .

    "noUnusedParameters": false,
     .
     .

}

noUnusedParameters
未使用のパラメータに対して警告をします。
初期値はfalseなのですが、なぜかtrueになっていました。。。。
tsconfigは意味を理解してちゃんと設定しましょう。。。

その他の解決方法

@ts-ignoreを記述する

@ts-ignoreをコメントで記述すると、コンパイルのチェックをパスすることができます。明示的にパスした理由をコメントに残しておきましょう。


import Express from 'express';

const app = Express();

//@ts-ignore TS6133: 'req' is declared but its value is never read.
app.get('/', (req, res) => res.send('API Running'));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

上記のようにエラーメッセージを記述すると良いそうです。

無視したい部分に_をつける


import Express from 'express';

const app = Express();

app.get('/', (_req, res) => res.send('API Running'));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));


上記のようにreqの先頭に_をつけることによって、コンパイルチェックを回避することができます。
ただ、reqが呼び出されているのか、いないのか見通しが悪いですね。。。

まとめ

コンパイルの設定についてちゃんと調べましょう。(戒め)
ts-ignoreによるコンパイルチェックの回避は
型定義がされていないパッケージのコンパイルチェックを回避するシーンで使うと思いますので、覚えておきましょう!

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
6