Skip to content

Tuple type not inferred when calling generic function #6310

Closed

Description

Tuple types aren't always inferred when calling generic functions. For example:

function identity<A>(value: A): A {
    return value
}

// works
const [a1, b1]: [number, string] = [1, 'a']

// works
const [a2, b2]: [number, string] = identity<[number, string]>([1, 'a'])

// breaks
const [a3, b3]: [number, string] = identity([1, 'a'])

Output:

foo.ts(12,7): error TS2322: Type '(number | string)[]' is not assignable to type '[number, string]'.
  Property '0' is missing in type '(number | string)[]'.

See also #2189, #4136, #6037.

Activity

  1. DanielRosenwasser commented on Jan 2, 2016

    @DanielRosenwasser
    Member

    This is because the array expression needs to be contextually typed by a tuple-like type so that we can infer your type argument as a tuple. You've enforced that when you explicitly gave a type argument, but not in the last example.

    One way you could achieve what you want is to add a tuple-like constraint for your type parameter:

    function identity<A extends [void] | {}>(value: A): A {
        return value
    }
  2. zpdDG4gta8XKpMCd commented on Jan 4, 2016

    @zpdDG4gta8XKpMCd

    that's the most interesting identify function I've seen so far

  3. locked and limited conversation to collaborators on Jun 19, 2018
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

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions