Nate Thompson
Nate Thompson

Reputation: 395

Is there a Typescript way of adding properties to a prototype?

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)"

Upvotes: 2

Views: 850

Answers (1)

Konrad
Konrad

Reputation: 24661

You can do this like that:

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

Based on this Extending functionality in TypeScript

Upvotes: 3

Related Questions