In one of my modules I use an optional tuple for a function result:
function ruleFromPosition(position): [string, number] | undefined;
and assign this to local vars in my unit tests:
let [ruleName, ruleIndex] = ruleFromPosition(position);
This results in the error:
Type must have a 'Symbol.iterator' method that returns an iterator.
I could re-write this statement as:
let [ruleName, ruleIndex] = ruleFromPosition(position)!;
, which compiles, but that disallows for nullable checks. What's the correct way to use the tuple?
This is not a TypeScript "problem". You just can't destructure undefined:
let [a, b,] = undefined;
BOOM: Uncaught TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
(see exploringjs, destructuring)
Since your function has the propability of returning undefined, TypeScript won't compile. You can:
function ruleFromPosition(position): [string, number] | undefined {
if (position > 1) return undefined;
return ['1', 0];
}
const result = ruleFromPosition(1);
if (result) {
let [ruleName, ruleIndex] = result;
}
function ruleFromPosition(position): [string | undefined, number | undefined] {
if (position > 1) return [undefined, undefined];
return ['1', 0];
}
let [ruleName, ruleIndex] = ruleFromPosition(0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With