TS2349:无法调用类型缺少调用签名的表达式

时间:2019-10-09 17:28:43

标签: reactjs typescript

我知道此问题已在其他帖子中讨论,但我仍然不知道如何使它工作-我遇到了错误:

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

1 个答案:

答案 0 :(得分:3)

编译器不能确定array中包含的元素确实是一个函数,因为您已将其声明为并集string | Function

要解决此问题,请声明array为嵌套元组[string, Function][]

const func = (): string => 'hi';
const array: [string, Function][] = [['string', func]];
const response = array[0][1];
response(); 

Playground

或使用typeof type guard检查类似的功能

const func = (): string => 'hi';
const array: (string | Function)[][] = [['string', func]];
const response = array[0][1];

if (typeof response === "function") {
    response()
}

Playground