prefer-type-fest-string-length
Require TypeFest StringLength over StringToArray<T>['length'].
Targeted pattern scopeโ
This rule reports StringToArray<T>['length'] indexed-access type patterns and prefers the canonical StringLength<T> from type-fest.
What this rule reportsโ
TSIndexedAccessTypenodes of the shapeStringToArray<T>['length'].- Direct, aliased, and namespace-qualified
StringToArrayreferences imported fromtype-fest.
Detection boundariesโ
- Reports
StringToArray<T>['length']with exactly one type argument forwarded. - Autofixes by replacing the indexed-access type with
StringLength<T>and inserting atype-festimport when absent. - Does not autofix where the
StringLengthidentifier is shadowed by a type parameter in scope. - Does not flag
StringToArray<T, Options>['length'];StringToArrayoptions can change non-literal string behavior. - Does not flag
StringToArray<T>[0]or other non-'length'index expressions. - Does not flag local
StringToArrayhelpers that are not imported fromtype-fest. - Does not flag
StringToArrayreferences shadowed by an enclosing type parameter.
Why this rule existsโ
StringLength<T> is the canonical TypeFest utility for computing the length of a string type.
The pattern StringToArray<T>['length'] is equivalent only for the default one-argument StringToArray<T> form, but it exposes an implementation detail: turning the string into a tuple or array and then reading its length. StringLength<T> states the intent directly and keeps the type expression shorter.
โ Incorrectโ
import type { StringToArray } from "type-fest";
type EventNameLength = StringToArray<"user.created">["length"];
โ Correctโ
import type { StringLength } from "type-fest";
type EventNameLength = StringLength<"user.created">;
Behavior and migration notesโ
StringLength<S>returns the length of a literal string andnumberfor non-literal strings.StringLength<S>is implemented asStringToArray<S>['length']in TypeFest, so the one-argument migration is safe.StringToArray<S, { mapNonLiteralsDirectly: true }>['length']is intentionally ignored because that option changes how non-literal string parts are represented.
ESLint flat config exampleโ
import typefest from "eslint-plugin-typefest";
export default [
{
plugins: { typefest },
rules: {
"typefest/prefer-type-fest-string-length": "error",
},
},
];
When not to use itโ
Disable this rule if your codebase intentionally documents the intermediate StringToArray<T> representation and wants to keep the length extraction visually tied to that intermediate array form.
Package documentationโ
TypeFest package documentation:
Source file: source/string-length.d.ts
/**
* Returns the length of the given string.
*
* @example
* ```
* import type {StringLength} from 'type-fest';
*
* type A = StringLength<'abcde'>;
* //=> 5
* ```;
*/
Rule catalog ID: R126