【问题标题】:How to Declare and Destructure a Tuple Array in a for..of Loop in TypeScript?如何在 TypeScript 的 for..of 循环中声明和解构元组数组?
【发布时间】:2021-12-15 12:02:19
【问题描述】:

我在测试文件中有以下 JavaScript 代码:

for (let [input, expected] of [
  ['<h1>test</h1>', ['</h1>']],
  ['<h1><b>test</b></h1>', ['</h1>', '</b>']],
  ['<h1><b>test</b> lol</h1>', ['</h1>']],
]) {
  const result = functionToTest(input);
  for (let i in expected) {
    if (result[i] !== expected[i]) {
      throw Error("test failed")
    }
  }
}

TypeScript 不接受此代码,因为 functionToTest 期望 string 而 TypeScript 认为 input 具有类型 string | string[]

一个可行的方法是将我的测试数据放在一个单独的变量中,并将其类型声明为元组列表:

const testData: [string, string[]][] = [
  ['<h1>test</h1>', ['</h1>']],
  ['<h1><b>test</b></h1>', ['</h1>', '</b>']],
  ['<h1><b>test</b> lol</h1>', ['</h1>']],
]

for (let [input, expected] of testData) {
  const result = listClosingTagsAtEnd(input);
  for (let i in expected) {
    if (result[i] !== expected[i]) {
      throw Error("test failed")
    }
  }
}

但是我希望 必须创建一个变量来存储我只需要一次的数​​据。当它在 for 循环中声明时,我更喜欢它。

我尝试在 for 循环中使用 let [input, expected]: [string, string[]] of 进行类型声明,但收到错误 The left-hand side of a 'for...of' statement cannot use a type annotation.

我还尝试在 for 循环中的测试数据声明之后添加 : [string, string[]],但 TypeScript 认为我使用的是 JavaScript label

如何在将测试数据声明保留在 for 循环中的同时正确键入解构?

【问题讨论】:

    标签: typescript destructuring for-of-loop


    【解决方案1】:

    我自己偶然发现了这一点,只是“尝试随机的事情”,所以我想将它发布到 Stack Overflow,以防其他人遇到同样的问题。以下是你的做法:

    for (let [input, expected] of <[string, string[]][]>[
      //                          ^--------------------^
      //                             type declaration
      ['<h1>test</h1>', ['</h1>']],
      ['<h1><b>test</b></h1>', ['</h1>', '</b>']],
      ['<h1><b>test</b> lol</h1>', ['</h1>']],
    ]) {
      const result = functionToTest(input);
      for (let i in expected) {
        if (result[i] !== expected[i]) {
          throw Error("test failed")
        }
      }
    }
    

    编辑:哇,在this stack overflow answer 上找到了另一个解决方案!只需在文字后添加as const

    for (let [input, expected] of [
      ['<h1>test</h1>', ['</h1>']],
      ['<h1><b>test</b></h1>', ['</h1>', '</b>']],
      ['<h1><b>test</b> lol</h1>', ['</h1>']],
    ] as const) {
    //   ^---^
    //    HERE
      const result = functionToTest(input);
      for (let i in expected) {
        if (result[i] !== expected[i]) {
          throw Error("test failed")
        }
      }
    }
    

    在这种情况下,TypeScript 认为 input 具有 "&lt;h1&gt;test&lt;/h1&gt;" | "&lt;h1&gt;&lt;b&gt;test&lt;/b&gt;&lt;/h1&gt;" | "&lt;h1&gt;&lt;b&gt;test&lt;/b&gt; lol&lt;/h1&gt;" 类型,这确实是对 input 类型的最准确描述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 2020-03-27
      • 2017-10-28
      相关资源
      最近更新 更多