How to include a prototype in typescript

I am learning angular 2 and I wrote a ts definition for the truncate method that 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 to import this into another typescript module, or at least make it available for use globally.

+5
source share
3 answers

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

How to import this into another typescript module, or at least make it available for use around the world.

Move it to stringExtenions.ts file:

 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 as:

 import "./stringExtensions" 

More details

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

+9
source

In my case TypeScript 2.3.4 use

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

TypeScript Document Extending Global / Module Area from Modules

+3
source

All Articles