【发布时间】: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