Quantcast
Channel: Extend Basic Types in TypeScript, Error: "_this is not defined..." - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Extend Basic Types in TypeScript, Error: "_this is not defined..."

$
0
0

I am trying to rewrite some of my JavaScript code in TypeScript. Some of this code has references to an extension I added to the string object prototype.

String.prototype.format = function () {    var formatted = this;    for (var i = 0; i < arguments.length; i++) {        formatted = formatted.replace(            RegExp("\\{"+ i +"\\}", 'g'), arguments[i].toString());    }    return formatted;};

However adding this with type script has been quite challenging.

I have seen examples where you declare an extension of a basic interface then assign an function to the prototype to match the interface and provide your functionality. Like so...

interface String {    showString: () => string;}String.prototype.showString = (): string {    return this;};

Except this errors because "_this is not defined..."

The other things I have tried is to create a new class to extend string...

export class MoreString extends string {}

However this also does not work because you can only extend classes and string/String are not classes but built in types.

What is the simplest way to extend String and access my extension method?


Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>