Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
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]|\b\w|\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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Rather than polluting the String prototype, I'd suggest creating a function camelCase(str: string): string that takes in the string you want to camel case and returns it after being camelCased. Something like

export const camelCase = (str: string): string => {
  return str.replace(/[^a-z ]/gi, '').replace(
    /(?:^\w|[A-Z]|\b\w|\s+)/g,
    (match: any, index: number) => {
      return +match === 0
        ? ''
        : match[index === 0 ? 'toLowerCase' : 'toUpperCase']();
      },
    );
}

And now it can be imported like import { camelCase } from './utilties'; and called like camelCase('Hello World!');

This will lead to the function being more standalone, robust, and more easily tested than trying to modify the String prototype, plus, prototype modification isn't common anymore.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!