javascript - 如何在 typescript 中包含原型(prototype)

标签 javascript typescript angular

我正在学习 angular 2,我已经为我想在我的一项服务中使用的 chop 方法编写了一个 ts 定义。

chop .ts

interface String {
    truncate(max: number, decorator: string): string;
}

String.prototype.truncate = function(max, decorator){
   decorator = decorator || '...';
   return (this.length > max ? this.substring(0,max)+decorator : this);
};

如何将其导入另一个 typescript 模块或至少使其可在全局范围内使用。

最佳答案

在 Ionic 3 Angular 4 应用程序中使用 typescript 2.3.4 我创建了一个名为 stringExtensions.ts 的文件并将其放入其中

export { } // to make it a module

declare global { // to access the global type String
  interface String {
      truncate(max: number, decorator: string): string;
  }
}

// then the actual code
String.prototype.truncate = function(max, decorator){
   decorator = decorator || '...';
   return (this.length > max ? this.substring(0,max)+decorator : this);
};

关于javascript - 如何在 typescript 中包含原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38579273/

相关文章:

javascript - 即使事件未执行,事件监听器也会立即触发

asp.net - 如何在 ASP.Net MVC 中从 JavaScript 转换为 TypeScript?

typescript - 为什么通用类型 "T extends ' a' | 'b'“在检查参数是否等于联合类型值的情况下未正确解析?

angular - 为自定义属性实现双向数据绑定(bind)

angular - Angular2中自定义指令和组件之间的通信

angular - 发生未处理的异常 : Cannot find module '@angular/compiler-cli' with ng serve

javascript - 使用他们的 API 构建维基百科查看器,总是出现错误

javascript - 验证和 ajax 其中之一不起作用

ASP.NET javascript 调试在 2 个项目中不起作用

javascript - 识别带有一个异步函数调用的嵌套 FOR 循环和 IF 语句何时完成