Peter
Peter

Reputation: 7804

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.

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.

Upvotes: 13

Views: 13033

Answers (3)

Peter
Peter

Reputation: 7804

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

Upvotes: 22

user3020652
user3020652

Reputation: 41

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

Upvotes: 4

basarat
basarat

Reputation: 275849

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"

More

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

Upvotes: 12

Related Questions