【问题标题】:Iterating with TypeScript使用 TypeScript 进行迭代
【发布时间】:2021-03-02 01:49:34
【问题描述】:

在每次迭代期间您只想使用迭代的键(索引)时,如何迭代 N 次?没有要迭代的数组 - 您可以创建一个像 [...Array(num)] 这样的数组并在其上调用 map()forEach(),但是如何在每次迭代中使用密钥而不使用项目(在这种情况下是undefined) 并且没有 TypeScript 编译器抱怨它:

项目已声明,但其值从未被读取

这是旧 for 循环的用例还是可以以更简单/更安全的方式完成?

{[...Array(totalNum)].map((item: any, key: number) => {
    // if I console.log(item), tsc won't moan, but clearly not a solution
    return (
        <SomeComponent key={key}>
        </SomeComponent>
    )
})}

【问题讨论】:

  • 您在以“更简单/更安全的方式”寻找什么?现在,它读起来很有意见,可能因此被关闭。

标签: javascript typescript


【解决方案1】:

在参数前加_表示故意不使用参数可以解决警告:

[...Array(totalNum)].map((_item, key) => {

(请注意,不需要显式声明参数的类型;它只是在这里增加了额外的语法噪音)

如果你想完全删除未使用的参数,你可以用Object.keys遍历数组的键:

Object.keys([...Array(totalNum)]).map((key) => {

【讨论】:

  • 值得注意的是,抱怨未使用变量的不是打字稿而是 tslint。仅当规则配置为 "no-unused-variable": [true, {"ignore-pattern": "^_"}] 时,使用 _ 前缀变量才有效
  • 这不仅仅是一个 TSLint 错误,它也是一个 TS 错误。例如stackoverflow.com/questions/44565671/…
【解决方案2】:

我不得不在我的代码库中做很多这样的事情,我做了一个方便的助手,叫做mapTimes()

/** Returns an array of the return value of `fn` run `times` number of times. */
export function mapTimes<T>(times: number, fn: (index: number) => T): T[] {
  const arr: T[] = []

  for (let i = 0; i < times; i++) {
    arr.push(fn(i))
  }

  return arr
}

我基本上只是构建一个数组,其值与其索引相同。然后你传递一个函数来映射它。

用法:

{mapTimes(totalNum, (key: number) => {
    return (
        <SomeComponent key={key}>
        </SomeComponent>
    )
})}

【讨论】:

    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 2014-09-25
    • 2020-08-08
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多