Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda