Borislav Hadzhiev
Sat Feb 26 2022·2 min read
Photo by David Preston
To extend Date.prototype in TypeScript:
date.extensions.ts
file.Date
interface and add the extension method.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
, 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.
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.
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.