jameshfisher
jameshfisher

Reputation: 36397

TypeScript: Duplicate identifier in function type

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) { }

Upvotes: 1

Views: 1990

Answers (1)

Jeffery Grajkowski
Jeffery Grajkowski

Reputation: 4061

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.

Upvotes: 3

Related Questions