Skip to main content

prefer-ts-extras-array-last

Require arrayLast from ts-extras over direct array[array.length - 1] access.

Targeted pattern scopeโ€‹

This rule only matches direct last-element index access (receiver[receiver.length - 1]) where the receiver expression can be reused unchanged in arrayLast(receiver).

  • Direct last-element index patterns (array[array.length - 1]).

Syntactically similar alternatives are intentionally out of scope unless they preserve the same AST shape.

What this rule reportsโ€‹

This rule reports direct receiver[receiver.length - 1] access sites that can be safely replaced with arrayLast(receiver).

  • Direct last-element index patterns (array[array.length - 1]).

Why this rule existsโ€‹

arrayLast makes last-element access explicit and keeps type inference behavior consistent with other ts-extras array helpers.

  • Last-element access is easier to audit in large codebases.
  • Tuple/readonly array access patterns are standardized.
  • Helper-driven access reduces repeated inline index arithmetic.

โŒ Incorrectโ€‹

const last = values[values.length - 1];

โœ… Correctโ€‹

const last = arrayLast(values);

Behavior and migration notesโ€‹

  • Runtime behavior matches array[array.length - 1].
  • Empty arrays still produce undefined.
  • Equivalent index expressions with extra wrappers should be reviewed manually during migration.

Additional examplesโ€‹

โŒ Incorrect โ€” Additional exampleโ€‹

const last = rows[rows.length - 1];

โœ… Correct โ€” Additional exampleโ€‹

const last = arrayLast(rows);

โœ… Correct โ€” Repository-wide usageโ€‹

const lastStep = arrayLast(steps);

ESLint flat config exampleโ€‹

import typefest from "eslint-plugin-typefest";

export default [
{
plugins: { typefest },
rules: {
"typefest/prefer-ts-extras-array-last": "error",
},
},
];

When not to use itโ€‹

Disable this rule if direct index expressions are mandated by local style rules.

Package documentationโ€‹

ts-extras package documentation:

Source file: source/array-last.ts

/**
* Return the last item of an array with stronger typing for tuples.
*
* This provides better type safety than `array[array.length - 1]` or
* `array.at(-1)`.
*
* @category Improved builtin
*
* @example
* ```
* import {arrayLast} from 'ts-extras';
*
* const tuple = ['abc', 123, true] as const;
* const last = arrayLast(tuple);
* //=> true
* // ^? true
*
* const array = ['a', 'b', 'c'];
* const maybeLast = arrayLast(array);
* //=> 'c'
* // ^? string | undefined
*
* // Empty arrays
* const empty: string[] = [];
* const noLast = arrayLast(empty);
* //=> undefined
* // ^? string | undefined
* ```;
*/

Rule catalog ID: R009

Further readingโ€‹

Adoption resourcesโ€‹