Search code examples
angularangular13

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?


Solution

    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.