You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
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)[]'.
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.
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.
Activity
DanielRosenwasser commentedon Mar 3, 2015
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.
rolyp commentedon Mar 3, 2015
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.DanielRosenwasser commentedon Mar 3, 2015
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.