如何在 Angular 中使用全局扩展?

Mig*_*ura 7 typescript angular angular12

在 Angular 12 应用程序上,我创建了以下扩展:

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

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

在 Angular 组件中使用时:

var number = stringValue.toNumber();
Run Code Online (Sandbox Code Playgroud)

我收到错误:

Property 'toNumber' does not exist on type 'string'.
Run Code Online (Sandbox Code Playgroud)

在 Angular 中使用此类扩展的最佳方式是什么?

我需要更改创建扩展的方式吗?

Ame*_*mer 8

您可以通过以下方式实现此目的:

  • 您需要在全局接口中定义扩展方法的签名。要么将其放在单独的文件中,例如在src文件夹下创建一个global.d.ts文件。或者将其添加到下面进一步的方法的实现文件中:
declare global {
  interface String {
    toNumber(): number | null;
  }
}
export {}; // to define this file as a module
Run Code Online (Sandbox Code Playgroud)
  • string-extension.ts在文件夹下任意位置的文件中添加扩展方法的实现src,内容如下:
Object.defineProperty(String.prototype, "toNumber", {
  value(this: string) {
    return Number(this) || null;
  }
});
export {}; // to define this file as a module
Run Code Online (Sandbox Code Playgroud)
  • string-extension.ts文件导入到app.module.ts以使扩展全局可用:
 import 'PATH_TO_YOUR_FILE/string-extension'  
Run Code Online (Sandbox Code Playgroud)