【问题标题】:Typescript: Can't index an array that is being returned from a function打字稿:无法索引从函数返回的数组
【发布时间】:2020-06-22 22:40:17
【问题描述】:

我想索引一个正在构造并从函数返回的数组,但出现错误:

Element implicitly has an 'any' type because expression of type '3' can't be used to index type 'ArrFunc'.
  Property '3' does not exist on type 'ArrFunc'

这是我在 Typescript 操场上重新创建的代码以显示我的问题。

type ArrFunc = () => number[];
const arrFunc:ArrFunc = () => [1, 2, 3, 4];

console.log(arrFunc[3]);

我不确定哪个“元素隐式具有‘任何’类型。”据我所知,上面示例中的所有内容都定义得很好。

提前致谢!

【问题讨论】:

    标签: javascript typescript typescript-typings


    【解决方案1】:

    数组是从arrFunc返回的,所以你只能在调用函数后访问数组中的元素。

    console.log(arrFunc()[3]);
    

    【讨论】:

    • 是的哈哈,我的问题一发布我就意识到了。感谢您的快速答复!
    【解决方案2】:

    真傻……

    显然我不能索引一个函数。为此,必须调用该函数。

    const arr = arrFunc();
    console.log(arr[3])  // No problem
    

    多么尴尬:D

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 2023-02-07
      • 2018-11-14
      • 2020-05-02
      • 2022-01-12
      • 2021-07-05
      • 1970-01-01
      相关资源
      最近更新 更多