Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!