Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to declare a function, getting error TS2384: Overload signatures must all be ambient or non-ambient

Tags:

typescript

I am declaring a function say getValue. Then I am defining this getValue. But I am getting error as

error TS2384: Overload signatures must all be ambient or non-ambient.

What does ambient overload signature mean? What does non-ambient signature mean? How do I define a declared function without getting this error?

declare function getValue(key:string):any;

function getValue(key:string):any{
    return key;
}
like image 517
Midhun Raj Avatar asked Mar 02 '23 19:03

Midhun Raj


1 Answers

declare means that you don't ever intend to provide a value for that variable. It says to the compiler:

"I know this value doesn't exist in the code you can see, but I promise you that it's defined somewhere that is available to this scope, and this is its type"

So there would be no need for declare if you also provide a concrete value. Either declare the function, meaning it is defined somewhere the typescript compiler can't see, or remove the declare line altogether and export the function itself for use wherever you want.

(Secondarily, declare is useful for academic explorations of the type system. You can declare a variable with with a type, without ever providing a value for it, and then inspect the types downstream where that variable is used. This usage is absolutely not intended for production code.)


What does ambient overload signature mean?

"ambient" means no implementation exists. This is triggered by the declare keyword. Overload signatures happen when you write the a function type multiple times, with different argument types/return types. By having the function mentioned on two lines, typescript interprets that as a function overload.

What does non-ambient signature mean?

It means that an implementation could exist for this function.

How do I define a declared function without getting this error?

You don't. If you want to write an implementation for a function, do not use the declare keyword for that functions type.

like image 66
Alex Wayne Avatar answered Apr 26 '23 05:04

Alex Wayne