How to use Global extension in Angular?
Asked Answered
O

1

7

On an Angular 12 application I created the following extension:

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

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

When using in an Angular's component:

var number = stringValue.toNumber();

I get the error:

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

What is the best way to use such extensions in Angular?

Do I need to change the way I am creating the extension?

Ordinarily answered 31/8, 2021 at 18:26 Comment(2)
I just quickly tested it in Stackbliz ==> stackblitz.com/edit/…. But it looks to be working fine.Heartbreaker
@Heartbreaker Strange. In my app it only worked when using Amer Yousuf implementationOrdinarily
I
8

You can achieve this with the following:

  • You need to define the signature of the extension method in the global interface. Either put it in a separate file, e.g. under the src folder create a global.d.ts file. Or add it to the file of the implementation of the method further below:
declare global {
  interface String {
    toNumber(): number | null;
  }
}
export {}; // to define this file as a module
  • Add the implementation of the extension method within file string-extension.ts anywhere under src folder, with the following content:
Object.defineProperty(String.prototype, "toNumber", {
  value(this: string) {
    return Number(this) || null;
  }
});
export {}; // to define this file as a module
  • Import the string-extension.ts file into app.module.ts to make the extension available globally:
 import 'PATH_TO_YOUR_FILE/string-extension'  
Inexcusable answered 31/8, 2021 at 19:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.