Angular 7 向原语添加扩展方法

标签 angular extension-methods typescript-typings angular7

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

字符串扩展.ts:

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

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

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

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

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

a.isNullOrEmpty is not a function

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

谢谢。

最佳答案

首先,创建全局 .d.ts. 文件来设置签名。

global.d.ts。

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

字符串扩展.ts:

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

现在在 main.ts 中导入扩展

 import './string-extension'  

关于Angular 7 向原语添加扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53206823/

相关文章:

npm @types org 包中的 TypeScript 类型

javascript - 如何在表的列中嵌入树结构

javascript - js中如何过滤对象数组?

javascript - 带 ng-sidebar 的 Angular 4,向右添加类

c#-3.0 - 在 C# 中的接口(interface)上具有扩展方法的伪多重继承?

typescript - 如何在 typescript 中使用 singleton() 在构造函数中传递值?

javascript - typescript :无法将值从 json 转换为 [number, number] 元组

javascript - 未捕获的类型错误 : Cannot read property 'addEventListener' of null Angular 6

c# - Linq 扩展方法和错误处理

c# - 具有向后导航的流畅接口(interface)(方法链接)