An error using an extra tuple as a function results in Typescript

In one of my modules, I use an optional tuple for the 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 an error:

The type must have a method "Symbol.iterator", which returns an iterator.

I could write this instruction as follows:

let [ruleName, ruleIndex] = ruleFromPosition(position)!;

which compiles, but this prohibits checking with a null value. What is the correct way to use a tuple?

+6
source share
1 answer

This is not a TypeScript problem. "You simply cannot destroy undefined:

let [a, b,] = undefined;

BOOM: Uncaught TypeError: Unable to read the "Symbol (Symbol.iterator)" property from undefined

(. exploringjs, destructuring)

undefined, TypeScript . :

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);
+3

All Articles