1

I'm want to add some additional functions to the Date prototype object. The problem is that TS will complain because the property that I'm create does not already exist on the object. I'm able to ignore the complaint with //@ts-ignore, but I would prefer not to use that if possible.

Parent.tsx

//@ts-ignore
Date.prototype.getShortDate = function () {
  return this.toLocaleDateString('en-us', {
    month: 'short',
    day: 'numeric'
  });
};
//Without ts-ignore I get -> "Property 'getShortDate' does not exist on type 'Date'.ts(2339)"

Child.tsx

//@ts-ignore
const shortDate = new Date().getShortDate();
//Without ts-ignore I get -> "Property 'getShortDate' does not exist on type 'Date'.ts(2339)"
Nate Thompson
  • 325
  • 2
  • 12
  • 3
    Don’t extend built-in prototypes! It’s bad practice (can conflict with future changes to the language, messes with enumerable properties if you declare them this way, makes it unclear where functions come from). Declare it in a module and import it where you need it instead. – Ry- Oct 11 '22 at 20:28
  • 1
    i extent builtins all the time, with all buit ins. the arguments you name do not bother me in any way or I just disagree - eg I know precisely where my extensions to builtins come from - even more so due to typescript. However, MDN has a warning against extending builtins for potential performance reasons. I have not met those but have this on my list - since many years. Cannot find that warning in mdn, maybe they removed it meanwhile? – citykid Oct 11 '22 at 20:44

1 Answers1

1

You can do this like that:

declare global { interface Date { getShortDate(): string; } }

Based on this Extending functionality in TypeScript

Konrad
  • 21,590
  • 4
  • 28
  • 64