LoginSignup
0
0

More than 3 years have passed since last update.

ESLint prefer-readonly-parameter-types の対応

Posted at

ESLintのエラー対応のメモです。

prefer-readonly-parameter-typesというルールを設定しているとこのようなエラーが出ます。

ESLint: Parameter should be a read only type(@typescript-eslint/prefer-readonly-parameter-types)

読み取り専用の変数(上の場合関数の引数)には readonly をつけろ、というものです。

プリミティブな型の場合は

const hoge = (fuga:Readonly<string>) => {
}

というように書いてやればOKなのですが、引数に独自のインターフェースを持ったオブジェクトの場合は、

const hoge = (fuga:MyObject) => {
}

オブジェクトのプロパティまで全てread onlyにしてやらないといけないのです。
インターフェースの中に更に別のインターフェースを型にもち、読み取り専用でなかったすると厄介です。

どうしたものかと調べると便利そうなパッケージがありました。

こちらのReadonlyDeepによりオブジェクトの中のプロパティまでreadonlyに変換することが出来ます。

const hoge = (fuga:ReadonlyDeep<MyObject>) = {
}

今回はとりあえずこれで回避。

付け焼き刃な対応なので prefer-readonly-parameter-types を設定するなら事前に型の設計をちゃんとやらないとダメですね:innocent:

0
0
0

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
  3. You can use dark theme
What you can do with signing up
0
0