我知道此问题已在其他帖子中讨论,但我仍然不知道如何使它工作-我遇到了错误:
TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'string | Function' has no compatible call signatures.
控制台记录了一个函数,但我不能调用它。
在此先感谢您的帮助。这是我的代码:
const func = (): string => 'hi';
const array: (string | Function)[][] = [['string', func]];
const response = array[0][1];
console.log(response); // ƒ () { return 'hi'; }
response(); // TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'string | Function' has no compatible call signatures
答案 0 :(得分:3)
编译器不能确定array
中包含的元素确实是一个函数,因为您已将其声明为并集string | Function
。
要解决此问题,请声明array
为嵌套元组[string, Function][]
const func = (): string => 'hi';
const array: [string, Function][] = [['string', func]];
const response = array[0][1];
response();
或使用typeof
type guard检查类似的功能
const func = (): string => 'hi';
const array: (string | Function)[][] = [['string', func]];
const response = array[0][1];
if (typeof response === "function") {
response()
}