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

250
Vistas
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 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