2017-03-02 62 views
1

我提供這樣一個基本功能的函數:從NPM模塊內的界面添加屬性

// File 1: Core function 
export const extensions = []; 
export interface ResultInterface { 
    fullname:string, 
    age:number 
} 

function maFunction():ResultInterface { 
    var o = { 
     fullname:"alex", 
     age:21 
    }; 
    extensions.forEach((extension) => o = extension(o)); 
    return o; 
} 

你可以從maFunction上面的代碼中看到的是可擴展的通過了extensions期待數組並應用這些函數。在用戶態

// File 2: Extensions 1 (installed via NPM) 
extensions.push(function (o) { 
    o.ageInMonths = o.age * 12; 
    return o; 
}); 


// File 3: Extensions 2 (installed via NPM) 
extensions.push(function (o) { 
    o.firstname = o.fullname.split(" ")[0]; 
    o.lastname = o.fullname.split(" ")[1]; 
}); 

現在:

例如,可以通過安裝NPM以下擴展名

// File 4: Userland execution 
var myVar = maFunction(); 

myVar.ageInMonths // error: Property 'ageInMonths' does not exist on type 'ResultInterface'. 
myVar.firstname // error: Property 'firstname' does not exist on type 'ResultInterface'. 
myVar.lastname // error: Property 'lastname' does not exist on type 'ResultInterface'. 

沒想到打字稿足夠聰明,檢測加屬性通過擴展。但是每個擴展如何手動添加它們?每個擴展如何擴展ResultInterface並添加它自己的屬性?

回答

0

我不認爲是有可能做到這一點,而無需修改的ResultInterface的.d.ts(看到這麼迴應的位置:Extend interface defined in .d.ts file

你可以做壽」什麼是使用Intersection types鍵入myVar和增加它與功能接口,你需要:

var myVar: ResultInterface & {ageInMonths: number, firstname: string, lastname: string} = maFunction(); 

你可以添加一個「類型的捷徑」是這樣的:

type ResultInterfaceAugmented = {ageInMonths: number, firstname: string, lastname: string}& ResultInterface; 
var myVar: ResultInterfaceAugmented = maFunction();