Using the techniques described in this question, I am attempting to use Moment.js to extend the Date
prototype in a TypeScript project.
Extending the Date
prototype works, as described:
interface Date {
myExtension: () => string;
}
if (!Date.prototype.myExtension) {
Date.prototype.myExtension = function(): string {
return 'some value derived from a date';
};
}
However, as soon as I import Moment.js, by adding the following line to my file, TypeScript invalidates my code, telling me that Property 'myExtension' does not exist on type 'Date'
.
import * as moment from 'moment';
Is there another way I should be declaring the Moment.js import?
Not sure, how moment
relates to your question - I assume here, that you want to add global types to Date.prototype
, that will be internally implemented by moment
.
You can augment a global type definition of a built-in type Date
by defining the types 1.) in their own .d.ts
file or 2.) in one of your existent file modules.
1. global declaration file
Create global.d.ts
(naming doesn't matter). Put Date
interface in it, which will be merged with the already existent Date interface from lib.d.ts
. Make sure, you do not have any top level export
or import
declarations in it to append types to the global namespace/scope. global.d.ts
will be automatically included in projects with a tsconfig.json
.
// global.d.ts:
interface Date {
myExtension: () => string;
}
2. file module
Wrap the definitions in a global context with declare global
:
// inside some file module with export/import
...
declare global {
interface Date {
myExtension: () => string;
}
}
Test it in App.ts
// use moment for implementation
import * as moment from "moment";
if (!Date.prototype.myExtension) {
Date.prototype.myExtension = function(): string {
return "some value derived from a date";
};
}
const d = new Date();
console.log(d.myExtension()); // some value derived from a date