Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 842
Peter Avatar asked Jul 26 '16 00:07

Peter


People also ask

How do you use a prototype in TypeScript?

Prototype is a creational design pattern that allows cloning objects, even complex ones, without coupling to their specific classes. All prototype classes should have a common interface that makes it possible to copy objects even if their concrete classes are unknown.

Does TypeScript support prototype?

The Prototype Property in TypeScript which is used to add properties and methods to an object. Return Value: This method does not returns any value. Example 1: JavaScript.

Is TypeScript prototype based?

Nope. Not at all. In fact, when TypeScript is transpiled back to JavaScript, prototypes are heavily used. But, I should add, if you go that direction you should expect to be using JavaScript syntax more heavily than TypeScript.

How do I make a prototype of an object?

getPrototypeOf() The Object. getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.


1 Answers

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);
};
like image 68
Peter Avatar answered Sep 22 '22 22:09

Peter