我有一个函数可以提供像这样的基本功能:
// 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
数组并应用这些函数来扩展。
例如,可以通过NPM安装以下扩展:
// 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];
});
现在在用户区:
// 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'.
我没想到 typeScript 会智能到可以检测通过扩展添加的属性。但是每个扩展如何手动添加它们呢?每个扩展如何扩展 ResultInterface
并添加它自己的属性?
最佳答案
我认为如果不修改 ResultInterface
的 .d.ts 是不可能做到这一点的(参见此处的回复:Extend interface defined in .d.ts file)
你可以做的是使用 Intersection types键入 myVar
并使用您需要的功能扩充它的接口(interface):
var myVar: ResultInterface & {ageInMonths: number, firstname: string, lastname: string} = maFunction();
您可以像这样添加“类型快捷方式”:
type ResultInterfaceAugmented = {ageInMonths: number, firstname: string, lastname: string}& ResultInterface;
var myVar: ResultInterfaceAugmented = maFunction();
关于typescript - 从 NPM 模块中向界面添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42552819/