如何使用全局扩充在 TypeScript 1.8 中扩展原生 JavaScript 类型?

How to extend native JavaScript types in TypeScript 1.8 using global augmentation?

我正在尝试使用 TypeScript 1.8 中的新全局扩充来扩展原生 JavaScript 类型,如 here 所述。但是,当扩展功能 returns 相同类型时,我遇到了问题。

Global.ts

export {};
declare global {
    interface Date {
        Copy(): Date;
    }
}

if (!Date.prototype.Copy) {
    Date.prototype.Copy = function () {
        return new Date(this.valueOf());
    };
}

DateHelper.ts

export class DateHelper {
    public static CopyDate(date: Date): Date {
        return date.Copy();
    }
}

我在尝试使用 DateHelper.ts 中定义的扩展时遇到以下错误 TS2322:

Type 'Date' is not assignable to type 'Date'.
Property 'toDateString' is missing in type 'Date'.

有人知道如何解决这个问题吗?

你可以这样做:

Global.ts:

interface Date 
{
    Copy: () => Date;
}

Date.prototype.Copy = function() 
{
    return new Date(this.valueOf());
};

在你的DateHelper.ts

import './Global';

export class DateHelper {
    public static CopyDate(date: Date): Date {
        return date.Copy();
    }
}