anonymous-dev
anonymous-dev

Reputation: 3519

Statements are not allowed in ambient contexts

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?

Upvotes: 1

Views: 8144

Answers (2)

Ben Willson
Ben Willson

Reputation: 11

This error is because of the name of the index.d.ts File Renmae the file to StringExtension.d.ts and it will work. The name of the file gives it the context it is looking for.

Upvotes: 0

Wing
Wing

Reputation: 9721

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.

Upvotes: 4

Related Questions