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

253
Visualizações
JS/TS Prototype Extension, doesn't work on specific instance of prototype

I have a Date prototype extension that I use in Angular project, defined as:

if (!Date.prototype.hasOwnProperty('toLocalISOString')) {
  Date.prototype.toLocalISOString = function (): string | null {
    try {
      const date = new Date(this.valueOf());
      const a = [
        { f: date.getFullYear(), pad: 4 },
        { f: date.getMonth() + 1, pad: 2 },
        { f: date.getDate(), pad: 2 },
        { f: date.getHours(), pad: 2 },
        { f: date.getMinutes(), pad: 2 },
        { f: date.getSeconds(), pad: 2 },
        { f: date.getMilliseconds(), pad: 3 }
      ];
      const s = a.map(d => d.f.toString().padStart(d.pad, '0'));
      return `${s[0]}-${s[1]}-${s[2]}T${s[3]}:${s[4]}:${s[5]}.${s[6]}`;
      //return `${s[0]}-${s[1]}-${s[2]}T${s[3]}:${s[4]}:${s[5]}.${s[6]}Z`;      //if using Z as identifier the time is considered UTC
    }
    catch {
      return null;
    }
  }

The extension is declared in my global.d.ts file as:

export { }
declare global {    
  interface Date {
    toLocalISOString(): string | null;
  }
}

With a function call in a component as below:

getAllSelect(startDate?: Date, endDate?: Date) {
    let params = new HttpParams();
    if (startDate && endDate)
    {      
       const d1 = new Date(startDate).toLocalISOString() ?? '';
       const d2 = new Date(endDate).toLocalISOString() ?? '';
    }

    'do stuff
}

if I use the function WITHOUT the new Date() initializer, i.e.

const d1 = startDate.toLocalISOString() ?? '';
const d2 = endDate.toLocalISOString() ?? '';

I get an error message that toLocalISOString is not a function even though startDate & endDate are both of type Date? if I include the new Date() initializer it works as intended.

Would anyone be able to shed some more light on the intricate differences between the two methods and why the prototype extension doesn't get recognized from the Date | null instance?

about 4 years ago · Juan Pablo Isaza
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