Issue
I don't understand what means the word ambient
in the following sentence:
A function implementation cannot be declared in an ambient context.
I'm not sure to understand the general meaning of the word, (English isn't my maternal language) and if there is a specific meaning here I don't get it as well.
I've tried to understand in my maternal language but couldn't get it in this context. It's something like current context
I'd say but it doesn't work out.
The message appeared because I was trying to declare
a class, which cannot be declared, only module
can. I've fixed it but still don't understand the meaning of the error message here.
Solution
Ambient simply means "without implementation".
Ambient declarations only exist in the type system and are erased at run-time:
// ambient module declaration
declare module "mymod" { /*... */ }
// ambient namespace declaration
declare namespace MyNamespace { /*... */ }
// ambient variable declaration
declare const myVar: string;
For example declare const myVar: string
is like a promise to the compiler: "Assume that there will be a const myVar
with type string
defined at run-time" (other cases analogue).
You also can think of ambient as the declare
keyword in TS. All type declarations like interfaces or type aliases are implicitly ambient by definition, as it is clear for the compiler, that these have no run-time impact.
declare type MyType = {a: string} // is valid
type MyType = {a: string} // shorter, so just leave "declare" out
"A function implementation cannot be declared in an ambient context."
As said, ambient declarations cannot contain run-time code, like:
declare module "mymod" {
function foo() { // error: An implementation cannot be declared in ambient contexts.
console.log("bar")
}
}
Given "mymod"
is a npm package, the implementation code would rather be in the main .js
file under "node_modules/mymod"
, and above types reside in a separate .d.ts
file.
Answered By - ford04
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.