indapublic
indapublic

Reputation: 2318

Extend base interface and export it

How I can to extend base interface and export it? For example:

export interface Date {
    /**
     * Original functions
     */
    getTime(): number;
    /**
     * My extend functions
     */
    getId(): number;

}

Date.prototype.getId = function (): number {
    return 1;
}

If I want to export Date prototype, I receive error

[ts] Property 'getId' does not exist on type 'Date'.

Only I can is create manually d.ts file

export interface Date {
    getTime(): number;
    getId (): number;
}

and import it

import {Date} from "myfile";

But it's not cool

Upvotes: 0

Views: 148

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164137

If you want to add methods to the Date prototype you'll need Global augmentation:

// myfile.ts

export {}; // you need this so the compiler understands that it's a module.

declare global {
    interface Date {
        getId(): number;
    }
}

Date.prototype.getId = function (): number {
    return 1;
}

Then when you import this file you should be able to use getId:

import "file1";
let d = new Date();
console.log(d.getId());

Upvotes: 2

Related Questions