1

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?

1 Answer 1

3

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 */ });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that makes sense. Since it returns a new array, I don't know if I agree with TypeScript's design decision of .concat() requiring its arguments to be of the same time as the array it was called on; it makes sense for something like .push() which modifies the existing array. The workaround gets the job done though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.