Skip to content

Tuple type vs. array-of-union-type #2189

Closed

Description

@rolyp

Have I made a silly mistake here? I thought the tuple type [string, number] was roughly equivalent to the array-of-union-type (string | number)[], and that the following was therefore legal:

function lengths (xs: string[]): [string, number][] {
   return xs.map((x: string) => [x, x.length])
}

However tsc 1.4 complains:

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

Activity

  1. DanielRosenwasser commented on Mar 3, 2015

    @DanielRosenwasser
    Member

    I believe (and others on the team should feel free to correct me) that this has to do with the way in which contextual typing takes effect (i.e. it doesn't take effect on the return type of a call expression).

    In other words, lengths's return type doesn't impact your call's type, and so the language computes the type (string | number)[].

    You can get the behavior you want by giving your lambda a return type.

    function lengths(xs: string[]): [string, number][] {
        return xs.map((x): [string, number] => [x, x.length]);
    }
  2. rolyp commented on Mar 3, 2015

    @rolyp
    Author

    Ah, interesting. Thanks.

    As an aside, I've become wary of adding types to lambdas: at least, adding parameter types seems to be broken (code which didn't type-check when the parameter type annotation was omitted type-checks fine with a suitable annotation, and then fails at runtime). I'll probably post an example at some point. It looks like the inferred type isn't being checked against the annotation, so the annotation is behaving like a cast.

    But here you're talking about adding a return type, which is certainly an improvement on my current workaround (which involves any <any> cast). Cheers.

  3. DanielRosenwasser commented on Mar 3, 2015

    @DanielRosenwasser
    Member

    Glad this helps, though, we'd definitely like to see an example where you run into the situation you mentioned if you can reproduce it.

  4. locked and limited conversation to collaborators on Jun 18, 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