如何在打字稿中包含原型

Pet*_*ter 9 javascript typescript angular

我正在学习角度2,我已经为我想要在我的一个服务中使用的truncate方法编写了一个ts定义.

truncate.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);
};
Run Code Online (Sandbox Code Playgroud)

如何将其导入另一个打字稿模块或至少使其可以全局使用.

bas*_*rat 11

如何将其导入另一个打字稿模块或至少使其可以全局使用.

将其移动到文件stringExtenions.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);
};
Run Code Online (Sandbox Code Playgroud)

并导入文件,如:

import "./stringExtensions"
Run Code Online (Sandbox Code Playgroud)

更多

https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html


Pet*_*ter 11

在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);
};
Run Code Online (Sandbox Code Playgroud)

  • 与其他示例相比,使用导出 {} 和声明全局 {} 对我来说是神奇的…然后郑重声明,我不需要在每个其他示例的使用范围中进行任何其他导入。谢谢彼得! (2认同)