Home > other >  Statements are not allowed in ambient contexts
Statements are not allowed in ambient contexts

Time:10-18

I am using firebase cloud functions and I use Typescript and I made a index.d.ts file in the src directory. I am trying to assign a function to String.prototype. But I get the following error on String.prototype

Statements are not allowed in ambient contexts.

and

An implementation cannot be declared in ambient contexts.

on function () {

export {};

declare global {
  interface String {
    capitalize(): string;
  }
}

String.prototype.capitalize = function () {
  return this.charAt(0).toUpperCase()   this.slice(1);
};

Why does this happen?

CodePudding user response:

These two things combined together are the problem:

I made a index.d.ts file

I am trying to assign a function to String.prototype.

A d.ts file is a TypeScript declaration file. These files only declare types and cannot contain implementation code hence your two errors:

Statements are not allowed in ambient contexts.

An implementation cannot be declared in ambient contexts.

Implementation code is code that is not a type annotation or an alternative way of describing this is implementation code is code that is executed during runtime.

You probably aren't intending to write a declaration file – they are often only used to add types to libraries which aren't written in TypeScript. As a result you should rename your file from index.d.ts to index.ts.

  • Related