sindresorhus/type-fest

Add `ArrayAt` type for stricter `Array.prototype.at()` with tuples

Open

#369 opened on Mar 1, 2022

View on GitHub
 (10 comments) (0 reactions) (0 assignees)TypeScript (471 forks)batch import
help wantedtype addition

Repository metrics

Stars
 (12,328 stars)
PR merge metrics
 (Avg merge 3d 5h) (11 merged PRs in 30d)

Description

See https://github.com/sindresorhus/ts-extras/issues/39 and https://github.com/microsoft/TypeScript/issues/47660.

const tuple = ['abc', 123, true] as const;

type First = ArrayAt<typeof tuple, 0>; // 'abc'
type Last = ArrayAt<typeof tuple, -1>; // true
type SecondToLast = ArrayAt<typeof tuple, -2>; // 123
type ThirdToLast = ArrayAt<typeof tuple, -3>; // 'abc'
type OutOfBounds = ArrayAt<typeof tuple, 999>; // should not compile since 999 does not extend 0 | 1 | 2 | -1 | -2 | -3
const array = ['abc', 123, true];

type First = ArrayAt<typeof tuple, 0>; // string | number | true
type Last = ArrayAt<typeof tuple, -1>; // string | number | true
type OutOfBounds = ArrayAt<typeof tuple, 999>; // string | number | true

Contributor guide