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
functiongetData<T>(arg: T): T{returnarg;}letresultArray=[getData("abcd"),getData(1234)];// Inferred as (string | number)[]// compare toletsimpleArray=["abcd",1234];// Inferred as (string | number)[]
This seems consistent with how the type of an array initialized to constant values would behave. Having it inferred as a tuple would create a problem if it is extended or modified later. If it was immutable or somehow its length was fixed then I believe it would be reasonable to infer it as a tuple.
One workaround is to annotate the return type explicitly:
Thank you for the explanation. This makes sense.
However, to elaborate on the use case, an issue occurs when funcArray has to be used in a function expecting a tuple.
interfaceFoo{a: string}interfaceBar{b: string}getData<T>(): T{returnnull;}varfuncArray=[this.getData<Foo>(),this.getData<Bar>()];//Inferred as (Foo | Bar)[]myFunc<T1,T2>(values: [T1,T2]): boolean{returnvalues[0]!==undefined&&values[1]!==null;}// Error: Argument of type '(Foo | Bar)[]' is not assignable to parameter of type '[Foo, Bar]'// Property '0' is missing in type '(Foo | Bar)[]'myFunc<Foo,Bar>(funcArray);
What is property '0'?
Explicitly annotating the return type is a valid workaround, but it is cumbersome to do every time the method is used. Is there a better and clean solution?
In a tuple, the types are treated more internally treat like this:
interfaceFuncArrayTuple<T1,T2>{0: T1;1: T2;}
Tuples are the least JavaScripty like type that TypeScript supports, basically intended to allow multiple values to be returned from a function. So not using them is one option. You could create a type alias, something like:
Activity
malibuzios commentedon May 4, 2016
I tried to simplify the example:
This seems consistent with how the type of an array initialized to constant values would behave. Having it inferred as a tuple would create a problem if it is extended or modified later. If it was immutable or somehow its length was fixed then I believe it would be reasonable to infer it as a tuple.
One workaround is to annotate the return type explicitly:
Another is to use a helper like
createTuple:mhegazy commentedon May 4, 2016
Tuple types are never inferred from a literal unless specified. so:
If tuples were inferred automatically that could be a huge breaking change, and would make array uses for a lot of valid scenarios errors.
AbhishekGarg commentedon May 5, 2016
Thank you for the explanation. This makes sense.
However, to elaborate on the use case, an issue occurs when
funcArrayhas to be used in a function expecting a tuple.property '0'?kitsonk commentedon May 5, 2016
Or probably better, have something return a tuple type, like: