In a test file, I have the JavaScript code shown below:
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")
}
}
}
However, TypeScript does not accept this code because functionToTest
expects a string
, and TypeScript believes that input
has type string | string[]
.
An alternate approach is to store the test data in a separate variable with declared type as a list of tuples:
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")
}
}
}
Despite this solution, I prefer not having to create an additional variable to hold data that is only used once. It was more convenient when the data was declared directly in the for loop.
I attempted to define types within the for loop using
let [input, expected]: [string, string[]] of
, but encountered the error The left-hand side of a 'for...of' statement cannot use a type annotation.
.
Additionally, adding : [string, string[]]
after declaring test data in the for loop resulted in TypeScript identifying it as a JavaScript label.
Is there a way to correctly specify destructuring types while keeping the declaration of test data inside the for loop?