Skip to content

Equivalent Tuple with Rest types not duck-typing properly #52496

Open

Description

Bug Report

A tuple type with a rest element doesn't duck-type properly to the similar tuple type, although they are conceptually identical, causing a ts2345 error to show up when trying to use one with the other.

The type I tested was a type defining a non-empty array. It looks like there's a bug because the location of the "non-empty item" in the definition matters for typescript, although there shouldn't be any difference in the kind of arrays that are accepted for each type.

🔎 Search Terms

  • tuple
  • rest

🕗 Version & Regression Information

Since 4.2 where rest params where allowed a the start of a tuple too

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about tuple

⏯ Playground Link

Playground link with relevant code

💻 Code

type FirstItem<T> = [T, ...T[]];
type LastItem<T> = [...T[], T];

const f0: FirstItem<number> = []
const l0: LastItem<number> = []

const f1: FirstItem<number> = [1]
const l1: LastItem<number> = [1]

const f2: FirstItem<number> = [1, 2]
const l2: LastItem<number> = [1, 2]

function foo(x: FirstItem<number>): void {
    // DO NOTHING
}

foo(f2) // OK
foo(l2) // ts2345

const x: number[] = [2, 3, 4]

foo([1, ...x]) // OK
foo([...x, 5]) // ts2345

🙁 Actual behavior

  • ts2345 is shown

🙂 Expected behavior

  • the two types should be considered equivalent and duck-typeable.

Activity

  1. Andarist commented on Jan 30, 2023

    @Andarist
    Contributor

    I didn't have time to analyze this completely to be sure but it might be related to this: #49138

  2. ahejlsberg commented on Jan 30, 2023

    @ahejlsberg
    Member

    While I can see that [T, ...T[]] and [...T[], T] effectively express the same concept (an array with at least one element), I'm not sure it is worth the extra complexity to detect and equate these types. If we did, we'd likely also have to detect and equate [T, T, ...T[]], [T, ...T[], T] and [...T[], T, T] and so on.

    This isn't related to #49138 (which has to do with a missing contextual type).

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

    SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions