【发布时间】:2018-07-23 03:47:11
【问题描述】:
我有一个返回代理的函数,它使用get 陷阱从多个对象推断函数。现在我需要能够键入这些函数,因为它们在编译时在技术上是已知的,但 TypeScript 就是无法弄清楚它们。如何让 TypeScript 识别这些函数以便能够将它们添加到我的界面中?
interface IObject {
(): IFunction;
addAMethod(name: string, fn: (...args: any[]) => any): void;
}
interface IFunction {
list: string[];
option: boolean;
}
const mainFunc: IObject = Object.assign(
(): IFunction => {
const context = {
list: [],
option: true,
};
return new Proxy(context, handler);
},
{
addAMethod(name: string, fn: (...args: any[]) => any) {
Object.assign(core, fn);
},
},
);
const handler = {
get(context: {[key: string]: any}, prop: string, receiver: IFunction) {
if (prop in context) {
return context[prop];
}
if (prop in core) {
return core[prop];
}
},
};
const core = {
evaluate: (val: any) => true,
doSomething: (val: any) => false
}
export default mainFunc;
现在这将允许以下操作:
import mainFunc from "./mainFunc"
mainFunc().evaluate('wow'); // Should return true
这当然不会返回真,而是表明evaluate() 不是IFunction 类型的一部分,这是真的。但是当我尝试添加它时,我得到另一个错误,我无法将函数分配给IFunction,因为它没有定义evaluate()。
// ...
interface IFunction {
list: string[];
option: boolean;
evaluate(val: any): boolean;
}
const mainFunc: IObject = Object.assign(
(): IFunction => {
const context = {
list: [],
option: true,
};
return new Proxy(context, handler); // Error happens here
},
// ...
);
// ...
const core = {
evaluate: (val: any) => true,
doSomething: (val: any) => false
}
输入'{列表:从不[];选项:布尔值; }' 不可分配给类型 'IFunction'。 '{ list: never[]; 类型中缺少属性 'evaluate'选项:布尔值; }'。
知道如何输入evaluate()吗?
【问题讨论】:
-
只是想了解
addAMethod的用法应该没有额外的name参数来命名正在添加的函数吗? -
@TitianCernicova-Dragomir 你说得对,我已经修改了。
标签: javascript typescript