Skip to content

Expressive Reversed type for tuples #60575

Closed

Description

@redpulp

⚙ Compilation target

ES2024

⚙ Library

5.6.3

Missing / Incorrect Definition

interface Array<T> {
    reverse: T[];
}

This loses all information of the order of reversed tuples, I usually have to use the following code to override the behaviour of Array.prototype.reverse

type ReversedTuple<T extends any[], R extends any[] = []> = ReturnType<T extends [infer F, ...infer L] ? () => Reverse<L, [F, ...R]> : () => R>;
type ReversedTupleOrArray<T> = T extends [any, ...any[]] ? Reverse<T> : T;

Sample Code

const myTuple: [number, string, string] = [1, 'hello', 'world']
const reversedTuple = myTuple.reverse() // (string | number)[]

Activity

  1. MartinJohns commented on Nov 24, 2024

    @MartinJohns
    Contributor

    Related: #13360 (comment)

    And in general reverse() is troublesome for tuples, because it modifies the array in-place.

  2. redpulp commented on Nov 24, 2024

    @redpulp
    Author

    And in general reverse() is troublesome for tuples, because it modifies the array in-place.

    Yeah tuples should be immutable by definition, so I get how this would be troublesome here. I only know of dirty tricks to avoid this (like [...array].reverse()) so I understand the issue, thanks for the comment

  3. locked as resolved and limited conversation to collaborators on Oct 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions