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.
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
:
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"
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
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
declare global {
interface Date {
format(format: string): string;
}
}
The TypeScript document Augmenting global/module scope from modules
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.