Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda