1

When trying to compile:

function foo(f: (number, number)=>boolean) {}

I get the error:

Duplicate identifier 'number'.

Why? What I'm intending to state is that f is a function that takes two arguments, each of type number, and returns a boolean. How do I state that?

For reference, the following do compile:

function foo2(f: (number) => boolean) { }

function foo3(f: (a: number, b: number) => boolean) { }

function foo4(f: (number, string) => boolean) { }

But the following does not (it generates exactly the same error, Duplicate identifier 'number'):

function foo5(f: (number, number[]) => boolean) { }

1 Answer 1

3

You have to name the parameters the function f takes in. So that's why foo3 works. foo2 and foo4 compile because the compiler takes those as the names and because there's no type assumes any type. They could be rewritten as:

function foo2(f: (number: any) => boolean) { }
function foo4(f: (number: any, string: any) => boolean) { }

Of course that's some confusing code.

With that in mind foo doesn't work because the compiler takes that to mean:

function foo(f: (number: any, number: any)=>boolean) {}

and yes you have a duplicate identifier number.

Sign up to request clarification or add additional context in comments.

2 Comments

Maan, I have to name the arguments? Is there any way around that? Obviously, the variable names are not logically required. (i.e., they're entirely erased at compile time.)
Nope there's no way around it. On the bright side it provides a good hint to anyone using your code about what's expected.

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.