Reputation: 6414
The following code compiles.
function myFunction(arg1:string, arg2:(msg:string)=>void){ /* do stuff */ }
var args = ["hello", function(msg){ /* do stuff */ }];
myFunction.apply(myFunction, args);
But the following code does not compile, even though the variable args
is of the same type as above.
function myFunction(arg1:string, arg2:(msg:string)=>void){ /* do stuff */ }
var args = ["hello"].concat(function(msg){ /* do stuff */ });
myFunction.apply(myFunction, args);
It throws the following error.
>> src/workspace.ts(20,29): error TS2345: Argument of type '(msg: any) => void' is not assignable to parameter of type 'string'.
Any idea why? Is this a bug in my code or a bug in the TypeScript compiler?
Upvotes: 1
Views: 1683
Reputation: 250852
In TypeScript, when you create an array, the type is inferred from the array members. The following snippet is an Array<string>
, or string[]
var a = ["hello"];
If you try to add another value to this array, it will have to be a string:
a.concat("A string");
If you added a function, it would warn you that it isn't compatible:
a.concat(() => { return 5; });
And this also applies in your example, even though you are doing it immediately, as you can tell by adding an allowable value:
["hello"].concat("A string");
You can get around this by widening the type of the array:
var args = (<any[]>["hello"]).concat(function(msg){ /* do stuff */ });
Upvotes: 3