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
並添加它自己的屬性?