Angular 7 为基元添加扩展方法

Angular 7 为基元添加扩展方法

问题描述:

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

I would like to add few methods to primitives. I have the following file:

string-extension.ts:

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

String.prototype.isNullOrEmpty = function (this: string): boolean {
    return !this;
};

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

I have a component which has the following code:

constructor () {
    let a = "asd";
    alert(a.isNullOrEmpty());
}

顶部没有添加导入.当我运行客户端时,它在那条线上崩溃了.

no import is added at the top. When I run the client, it crashes on that line.

a.isNullOrEmpty is not a function

当我检查代码时,我发现我的 string-extension.ts 文件没有包含在那里.我非常熟悉 C# 中的概念,但我对 TypeScript 中的概念不太熟悉,所以如果您需要更多信息,请提供.

When I inspect the code, i see that my string-extension.ts file wasn't included there. I am very familiar with the concept in C# but im not quite familiar with it in TypeScript, so if you need more info, ill provide.

谢谢.

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

first, create global .d.ts. file to set up the signature.

global.d.ts.

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

string-extension.ts:

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

现在在 main.ts 中导入扩展

 import './string-extension'