Miguel Moura
Miguel Moura

Reputation: 39474

Extension not found in Angular application

In an Angular 13 application I defined the following extension:

export { }

Object.defineProperty(String.prototype, "toNumber", {
  value: function(this: string) {
    return this.trim() ===  '' ? null : Number(this) || null;
  }
});

Then I use it the following way:

this.userId = value.get('userId')?.toNumber() ?? undefined;

But I get the compilation error:

Property 'toNumber' does not exist on type 'string'.

I didn't get this error I a previous Angular version application.

What am I missing?

Upvotes: 0

Views: 191

Answers (1)

Anton Hirov
Anton Hirov

Reputation: 351

  1. Add a new declaration to your extensions.ts file:
export {};

declare global {
    interface String {
        toNumber(): number;
    }
}

Object.defineProperty(String.prototype, "toNumber", {...});
  1. Don't forget to import this file: import "../extensions";
    Mode details here.

Upvotes: 1

Related Questions