10

I have a namespace in typescript that looks like this :

export declare namespace MyNamespace {
    const myFunc = (a:number) => 3;
}

My compiler complains about the function that :

TS1254: A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference

What is this error trying to tell me? I cannot have a function as a const within a namespace?

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225
  • 3
    ```export declare namespace MyNamespace { const myFunc: (a:number) => 3; }``` – Roberto Zvjerković Nov 11 '20 at 13:07
  • 5
    "ambient context" is basically the stuff that doesn't exist at runtime. It's where all the types reside at compile time and it's removed later. If you `declare` something, it's within the ambient context, as *that* is what `declare` does - makes something compile time only construct. Some parts [here](https://stackoverflow.com/a/28818850/) directly talk about ambient context. With all that said, the error is basically trying to tell you that you're writing code in something where you shouldn't have code (ambient because you've added `declare`). – VLAZ Nov 11 '20 at 13:08
  • 1
    If I replace the "=" with a ":" then it works for simple problems like the func above, but more complex functions I run into a whole host of problems. eg const sizeResolver : (val = false) => 1;.... says that "A parameter initializer is only allowed in a function or constructor implementation." – Oliver Watkins Nov 11 '20 at 13:18
  • 2
    In general, you could just drop the namespaces. They aren't deprecated per se but the modules system basically supersedes them. I see a lot of questions that stem from people using modules badly and I suspect the documentation around modules is not very good. Modules are more widely used and in general better documented (due to more usage), so switching to those will indirectly solve a lot of future problems. – VLAZ Nov 11 '20 at 13:26

1 Answers1

3

This error may happen if you are inside a d.ts file, which only allows type declarations. Try a .ts file instead!

Here is a related question: Initializers are not allowed in ambient contexts error when installing Blueprint

Elizabeth
  • 31
  • 3