2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

typescript-eslintのarray-typeルールについて

Posted at

はじめに

この記事ではtypescript-eslintのルールのうちarray-typeについて解説します。
typescript-eslintの他のルールについても別記事で解説し、最終的にReact開発を行うにあたって最適なルール設定を構築することを目的としています。

ルールについて

array-typeは配列の型宣言の方法を統一するためのルールです。"plugin:@typescript-eslint/strict"に設定すると有効になるルールの一つです。そして自動修正可能なルールです。
型宣言の方法はTという型を要素として持つ配列型を表現するためにT[]のようにする方法とArray<T>のようにする2種類があります。
このルールではこの2つのどちらかに統一するか、条件によってこの2つの記法を使い分けるという3つのルールが存在します。さらにそれらを通常の配列に対してと読み取り専用の配列に対してでそれぞれ定義可能です。
T[]で統一する場合は'array'Array<T>の場合は'generic'、金剛の場合は'array-simple'をオプションに指定します。
オプションの形式の型は以下のようになっています。

type Options = {
  default?: 'array' | 'generic' | 'array-simple',
  readonly?: 'array' | 'generic' | 'array-simple',
}

defaultreadonlyのどちらもarrayを指定した場合は以下のように統一します。

array
type Hoge = string[];
type Foo = readonly string[];
type Bar = (string | number)[];
type Fuga = readonly (string | number)[];

defaultreadonlyのどちらもgenericを指定した場合は以下のように統一します。

type Hoge = Array<string>;
type Foo = ReadonlyArray<string>;
type Bar = Array<string | number>;
type Fuga = ReadonlyArray<string | number>;

defaultreadonlyのどちらもarray-simpleを指定した場合は以下のように統一します。

type Hoge = string[];
type Foo = readonly string[];
type Bar = Array<string | number>;
type Fuga = ReadonlyArray<string | number>;

簡単に書ける時はT[]のように、複雑な組み合わせの時はArray<T>のように出し分けます。

ルールの採用について

配列の型定義方法を統一することで可読性が上がるので積極的に採用したいです。例え既存のプロジェクトに加えるとしても自動修正が可能なので低いハードルで簡単に採用できます。
そして設定するオプションは、defaultreadonlyで同じ値に設定したいです。読み取り専用という理由で異なるルールを設けると統一性に欠けることが理由です。
array-simpleは条件によって記法を変える必要があるので、記法のずれが目立つのと条件を開発者が把握する必要がある点から採用を避けたいです。
arraygenericですが、記述量の多さやデフォルトの記法でもあるのでarrayを採用するのが良いと考えています。

結果としてできた設定するルールは以下のようになります。

"@typescript-eslint/array-type": [
  "error",
  {
    "default": "array",
    "readonly": "array"
  }
]
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?