我正在开发一个服务定位器项目,并期待函数能够被传递,需要一个参数。检查函数签名
这里有一个片段:
"use strict";
/** Declaration types */
type ServiceDeclaration = Function|Object;
export default class Pimple {
/**
* @type {{}}
* @private
*/
_definitions: {[key: string]: ServiceDeclaration} = {};
/**
* Get a service instance
* @param {string} name
* @return {*}
*/
get(name: string): any {
if (this._definitions[name] instanceof Function) {
return this._definitions[name](this);
}
return this._definitions[name];
}
}
然而,当我尝试编译此我得到以下错误:
error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'ServiceDeclaration' has no compatible call signatures.
我试图创建一个新的类型:
type ServiceFunction = (container: Pimple) => any;
并试图更改instanceof Function
至instanceof ServiceFunction
,但后来我得到以下错误:
error TS2693: 'ServiceFunction' only refers to a type, but is being used as a value here.
我环顾四周,但一直未能找到任何检查传递的函数是否匹配指定签名的示例。
谢谢。我测试了几个变体,发现关键部分是先赋值'let f = this._definitions [name];'然后检查并使用局部变量。我不需要外部函数,我可以做'if(f instanceof Function){return f; }' –
@AndrewShell你说得对。我编辑过。 – Paleo