Javascript 如何在typescript中包含原型
我正在学习angular 2,我已经为我想在我的一个服务中使用的截断方法编写了一个ts定义 截断Javascript 如何在typescript中包含原型,javascript,typescript,angular,Javascript,Typescript,Angular,我正在学习angular 2,我已经为我想在我的一个服务中使用的截断方法编写了一个ts定义 截断 interface String { truncate(max: number, decorator: string): string; } String.prototype.truncate = function(max, decorator){ decorator = decorator || '...'; return (this.length > max ? th
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模块,或者至少使其可供全局使用
如何将其导入另一个typescript模块,或者至少使其可供全局使用
将其移动到文件stringextensions.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"
更多
在我的示例TypeScript 2.3.4中,使用
declare global {
interface Date {
format(format: string): string;
}
}
TypeScript文档在Ionic 3.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);
};
这可以编译,但truncate方法似乎不起作用。与其他示例相比,export{}&declare global{}对我来说是一种神奇的调味汁。。。作为记录,根据其他示例,我不必在我的使用范围内进行任何其他导入。谢谢你,彼得!是否有可能建立布尔型的原型?我可以添加一个类似于toggle()的方法吗?您可能应该把它作为另一个问题来问,但类似于Boolean.prototype.toggle=function(){返回this=!this}