簡體   English   中英

如何在打字稿中包含原型

[英]how to include a prototype in typescript

我正在學習角度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);
};

如何將其導入另一個打字稿模塊或至少使其可以全局使用。

如何將其導入另一個打字稿模塊或至少使其可以全局使用。

將其移動到文件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);
};

並導入文件,如:

import "./stringExtensions"

更多

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

在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);
};

在我的案例TypeScript 2.3.4中,使用

declare global {
    interface Date {
        format(format: string): string;
    }
}

TypeScript文檔從模塊擴充全局/模塊范圍

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM