简体   繁体   English

如何在打字稿中包含原型

[英]how to include a prototype in typescript

I am learning angular 2 and I have written a ts definition for a truncate method I want to use in one of my services. 我正在学习角度2,我已经为我想要在我的一个服务中使用的truncate方法编写了一个ts定义。

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

How do I import this into another typescript module or at least make it available to use globally. 如何将其导入另一个打字稿模块或至少使其可以全局使用。

How do I import this into another typescript module or at least make it available to use globally. 如何将其导入另一个打字稿模块或至少使其可以全局使用。

Move it to a file stringExtenions.ts : 将其移动到文件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);
};

And import the file like: 并导入文件,如:

import "./stringExtensions"

More 更多

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

using typescript 2.3.4 in an Ionic 3 Angular 4 app I create a file called stringExtensions.ts and put this in it 在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);
};

In my case TypeScript 2.3.4, use 在我的案例TypeScript 2.3.4中,使用

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

The TypeScript document Augmenting global/module scope from modules TypeScript文档从模块扩充全局/模块范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM