Angular 7向基元添加扩展方法

Ori*_*ael 2 extension-methods typescript-typings angular angular7

我想为基元添加一些方法。我有以下文件:

string-extension.ts:

interface String {
    isNullOrEmpty(this: string): boolean;
}

String.prototype.isNullOrEmpty = function (this: string): boolean {
    return !this;
};
Run Code Online (Sandbox Code Playgroud)

我有一个包含以下代码的组件:

constructor () {
    let a = "asd";
    alert(a.isNullOrEmpty());
}
Run Code Online (Sandbox Code Playgroud)

没有导入被添加到顶部。当我运行客户端时,它在该行崩溃。

a.isNullOrEmpty is not a function
Run Code Online (Sandbox Code Playgroud)

当我检查代码时,我发现我的string-extension.ts文件未包含在其中。我对C#中的概念非常熟悉,但对TypeScript不太了解,因此,如果您需要更多信息,请提供。

谢谢。

Sac*_*aka 5

首先,创建global .d.ts.文件以设置签名。

全球性

export {}; // this file needs to be a module
declare global {
  interface String {
        isNullOrEmpty(this: string): boolean;
  }
}
Run Code Online (Sandbox Code Playgroud)

string-extension.ts:

export {}; // this file needs to be a module
String.prototype.isNullOrEmpty = function (this: string): boolean {
    return !this;
};
Run Code Online (Sandbox Code Playgroud)

现在在main.ts导入扩展

 import './string-extension'  
Run Code Online (Sandbox Code Playgroud)

  • 我还认为,提及“global.d.ts”文件应该放置在哪里可能是明智的。如果我没记错的话,这应该是在 Angular 项目的根目录下,对吧? (2认同)