Reputation: 98
I am curious how the typescript compiler is interpreting the colon in the incorrect call to the function foo.
const foo = (bar: boolean) => {
return bar;
}
foo(bar: true) // ERROR "Expected 1 arguments, but go 2."
This implies that it is interpreting both "bar" and "true" as arguments. To be clear, I am just curious how the compiler is parsing this.
As a follow-up, are there any legitimate uses of a colon in a function call except for in an expression that would result in an argument as in:
const baz = (bin: {bar: boolean})=>{
return bin.bar
}
baz({bar: true})
Upvotes: 1
Views: 95
Reputation: 250196
There are two errors generated for that line. One is indeed that the function expects two arguments, but the other one is that ,
was expected (this is the error you will see if you run the compiler).
The language service tries to offer as much diagnostics as possible even on invalid code.
The parser will try to parse bar
as an argument (ie an expression) when it reaches the :
it will stop parsing the argument expression as :
can't be part of such an expression (at this time anyway). Then the compiler will continue to parse what it expects will be an argument list, and expect the ,
, but finding the :
instead. Now this is not a tragedy, the compiler will continue to parse the argument list, and interpret true
as the next argument expression.
The semantic checks, will then see this call (with two arguments) as an attempt to call a function with one parameter with two arguments and give an error on that.
The reason you are probably seeing in your IDE the semantic error over the syntactic one is because the semantic error is associated with the whole call(foo(bar: true)
) while the syntactic error is associated with just :
(and if you hover over :
you will see the ',' expected
error)
As to your follow-up :
can't be used directly in the argument list (like it can for example in C# for named arguments). The only valid use is if you use an object literal.
Upvotes: 2