はじめに
この記事ではtypescript-eslintのルールのうちawait-thenable
について解説します。
typescript-eslintの他のルールについても別記事で解説し、最終的にReact開発を行うにあたって最適なルール設定を構築することを目的としています。
ルールについて
await-thenable
はawait
の利用をthenableなオブジェクト以外に出来ないようにするルールで、"plugin:@typescript-eslint/recommended-requiring-type-checking"
で設定されるルールの一つです。
thenableなオブジェクトとはPromiseのようにthen
メソッドを持つオブジェクトのことを指します。
thenableなオブジェクトのイメージ
type Thenable<T> = {
then: (onfulfilled: (arg: T) => unknown) => unknown;
}
そしてこのルールは以下のようなケースで違反になります。
const hoge = () => 'hello';
await hoge();
解決するためには、hoge
自体をthenableなオブジェクトにするか、await
を外します。
thenableなオブジェクトにする
const hoge = async () => 'hello';
await hoge();
awaitを外す
const hoge = () => 'hello';
hoge();
ルールの採用について
不必要なawait
を配置することで想定外な動作を起こすことはありませんが、必要な場合でなければawait
を使えないようにすることでミスを減らせたり可読性を向上させられるのでこのルールは採用した方が良いと考えています。
このルールが有効であることでこのようなミスを防げる
const hoge = async () => 'hello';
// hogeの呼び出しを忘れている
await hoge;