【问题标题】:TS2349: Cannot invoke an expression whose type lacks a call signatureTS2349:无法调用其类型缺少调用签名的表达式
【发布时间】:2020-02-07 02:22:09
【问题描述】:

我知道这个问题已在其他帖子中介绍过,但我仍然不知道如何进行这项工作 - 我收到了错误:

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

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    编译器无法确定 array 中包含的元素确实是一个函数,因为您已将其声明为 union 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

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2016-03-30
      • 2017-10-11
      • 2020-05-17
      • 2017-12-19
      • 2017-07-14
      • 1970-01-01
      • 2019-01-05
      • 2018-05-09
      相关资源
      最近更新 更多