【问题标题】:How to extend native JavaScript types in TypeScript 1.8 using global augmentation?如何使用全局增强在 TypeScript 1.8 中扩展原生 JavaScript 类型?
【发布时间】:2016-08-22 23:21:05
【问题描述】:

我正在尝试使用 TypeScript 1.8 中新的全局增强来扩展原生 JavaScript 类型,如 here 所述。但是,当扩展函数返回相同类型时,我遇到了问题。

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'.

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

【问题讨论】:

    标签: typescript typescript1.8


    【解决方案1】:

    你可以这样做:

    全球.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();
        }
    }
    

    【讨论】:

    • 谢谢,这实际上会起作用,直到您执行以下操作: import {Predicate, Selector, Action, Comparer, Dictionary, Group} from 'PrototypeExtensions';声明 global{ interface Date { Copy: () => Date; } } Date.prototype.Copy = function() { return new Date(this.valueOf()); };当你这样做时,你需要添加声明全局部分,这反过来会给你 TS2322 错误。
    • 谢谢,我将使用这种方法,直到我们找到利用全局增强的解决方案。
    猜你喜欢
    • 2019-10-06
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 2022-11-12
    • 1970-01-01
    • 2016-10-23
    相关资源
    最近更新 更多