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

294
Visualizações
How to use Global extension in Angular?

On an Angular 12 application I created the following extension:

declare global {
  interface String {
    toNumber(): number | null;
  }
}

Object.defineProperty(String.prototype, "toNumber", {
  value: function(this: string) {
    return Number(this) || null;
  }
});

When using in an Angular's component:

var number = stringValue.toNumber();

I get the error:

Property 'toNumber' does not exist on type 'string'.

What is the best way to use such extensions in Angular?

Do I need to change the way I am creating the extension?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can achieve that like the following:

  • Under src folder create global.d.ts file to define the signature of the extension method, with the following content:
declare global {
  interface String {
    toNumber(): number | null;
  }
}
export {}; // to define this file as a module
  • Add the implementation of the extension method within file string.extension.ts anywhere under src folder, with the following content:
Object.defineProperty(String.prototype, "toNumber", {
  value: function(this: string) {
    return Number(this) || null;
  }
});
export {}; // to define this file as a module
  • Import the string.extension.ts file in app.module.ts:
 import 'PATH_TO_YOUR_FILE/string-extension'  
over 4 years ago · Santiago Trujillo 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