2016-12-27 65 views
0

我如何擴展基礎接口並導出它?例如:擴展基礎接口並導出它

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

} 

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

如果我要出口日期原型,我收到錯誤

[TS]房產 '的getId' 不上型 '日期' 存在。

只有我可以手動創建d.ts文件

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

並將其導入

import {Date} from "myfile"; 

,但如果你想方法添加到Date它的不冷靜

回答

2

您需要的原型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; 
} 

然後,當您導入此文件,你應該能夠使用getId

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

真棒!這就是我需要的!謝謝! – indapublic