我正在学习 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/