public-rules › TypeScript techs/typescript

Use one array type syntax

LOW1.0.0
When to apply Before writing or reviewing TypeScript array type annotations.

Write array types with the generic syntax, Array<T> and ReadonlyArray<T>, and enforce it with a lint rule.

Implementation

  • Use Array<string> and ReadonlyArray<string> rather than string[] and readonly string[].
  • Enforce with @typescript-eslint/array-type set to { default: 'generic' }.

This is a consistency convention; the two syntaxes are equivalent, and a project may choose T[] instead as long as it uses one. The generic form reads the same for mutable and readonly arrays and stays clear with complex element types, such as Array<string | number>.

Examples

Incorrect (counterexample):

const names: string[] = [];
const ids: readonly (string | number)[] = [];

Correct:

const names: Array<string> = [];
const ids: ReadonlyArray<string | number> = [];

Validation

Run the lint rule.

A project that consistently uses T[] instead is not a violation.