How to Extend Date.prototype in TypeScript


Borislav Hadzhiev

Last updated: Feb 26, 2022


Photo from Unsplash

Extend Date.prototype in TypeScript #

To extend Date.prototype in TypeScript:

  1. Create a date.extensions.ts file.
  2. Extend the Date interface and add the extension method.
  3. Import the extension method as import './date.extensions' before using it.

Here is the content of date.extensions.ts:

interface Date { getTimestamp(): number; } Date.prototype.getTimestamp = function () { return this.getTime(); };

And here is how we import and use the new getTimestamp method on the Date prototype:

import './date.extensions'; const date = new Date('2022-09-24'); // 👇️ 1663977600000 console.log(date.getTimestamp());

If I run my index.ts file, we can see that the getTimestamp method gets successfully invoked.

date prototype extended

We declared a new interface Date, which will get merged with the original Date interface.

In the interface, we created a getTimestamp method, which returns the number of milliseconds since the UNIX epoch.

Make sure to use a named function when extending the prototype, and not an arrow function, because arrow functions use the this of the enclosing scope, which is not what you want.

You could use this approach to extend Date.prototype with any method. Here is an example of a method that formats the date as yyyy-mm-dd.

This is the code in the date.extensions.ts file:

interface Date { format(): string; } Date.prototype.format = function () { return formatDate(this); }; function padTo2Digits(num: number) { return num.toString().padStart(2, '0'); } function formatDate(date: Date) { return [ date.getFullYear(), padTo2Digits(date.getMonth() + 1), padTo2Digits(date.getDate()), ].join('-'); }

And here is the index.ts file, which imports date.extensions.ts and makes use of the format method.

import './date.extensions'; const date = new Date('2022-09-24'); // 👇️ "2022-09-24" console.log(date.format());

Make sure to specify the correct path when importing the date.extensions.ts module.

When overriding Date.prototype, make sure your methods are not interfering with built-in method names, unless intentionally overriding them (which can be confusing).

Here is an example of how you would override the built-in getFullYear() method.

interface Date { getFullYear(): number; } Date.prototype.getFullYear = function () { return 100; };

And here is the code in our index.ts file.

import './date.extensions'; const date = new Date('2022-09-24'); // 👇️ 100 console.log(date.getFullYear());

Note that overriding built-in methods is confusing and should generally be avoided.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.