Search code examples
typescriptdeclarationtypescript-typingsbuilt-inmonkeypatching

Externally declaring monkey patches for built-in Node classes


I've written an NPM package called cached-date that monkey patches the Date class. It caches standard string representations of the date.

Every thing works great, except that I can't get my Typescript projects to recognize the type definitions included with the package:

// index.d.ts

declare interface Date {
    toCachedString(): string;
    toCachedDateString(): string;
    toCachedISOString(): string;
    toCachedJSON(): string;
    toCachedTimeString(): string;
    toCachedUTCString(): string;
}

The following code yields the compiler error Property 'toCachedISOString' does not exist on type 'Date':

// Typescript application

require('cached-date');
const date = new Date();
const isoStr = date.toCachedISOString();

The relevant portion of package.json is as follows:

// package.json

"main": "index.js",
"types": "index.d.ts",

Curiously, all is well when I move index.d.ts to my project's local declarations folder ("paths" in tsconfig.json), unchanged, and call it Date.d.ts.

Likewise, all is well when I put the following declaration in the app:

// application

export interface Date {
    toCachedString(): string;
    toCachedDateString(): string;
    toCachedISOString(): string;
    toCachedJSON(): string;
    toCachedTimeString(): string;
    toCachedUTCString(): string;
}

Is there a special way for me to externally merge declarations with built-in types? Thanks!


Solution

  • I figured it out. It's a bit embarrassing, actually. Just replace this:

    require("cached-date");
    

    with this:

    import "cached-date";
    

    Now Typescript pulls in the module's declarations and all is well.

    Interesting that this suggests a way to load modules without their declarations.