Typescript monkey patching doesn’t work for String


I create a new interface for String to add some utility methods using the technique of Monkey-patching.

interface String {
  toCamelCase(): string;
}

String.prototype.toCamelCase = function (): string {
    return this.replace(/[^a-z ]/gi, '').replace(
      /(?:^w|[A-Z]|bw|s+)/g,
      (match: any, index: number) => {
        return +match === 0
          ? ''
          : match[index === 0 ? 'toLowerCase' : 'toUpperCase']();
      },
    );
  };
  

in my controller when I call this new function: toCamelCase :

    const str: string = 'this is an example';
    const result = str.toCamelCase();
    console.log(result);

I have this error :

[Nest] 35664 – ERROR [ExceptionsHandler] str.toCamelCase is not a function
TypeError: str.toCamelCase is not a function

what is wrong with this implementation?

Source: JavaSript – Stack Overflow

November 7, 2021
Category : News
Tags: javascript | monkeypatching | nestjs | typescript | typescript2.0

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.