Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when using optional tuple as function result in Typescript

Tags:

typescript

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?

like image 423
Mike Lischke Avatar asked Aug 06 '17 09:08

Mike Lischke


1 Answers

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:

Check for the return value

function ruleFromPosition(position): [string, number] | undefined {
    if (position > 1) return undefined;

    return ['1', 0];
}

const result = ruleFromPosition(1);

if (result) {
  let [ruleName, ruleIndex] = result;
}

Return an destructurable array

function ruleFromPosition(position): [string | undefined, number | undefined] {
    if (position > 1) return [undefined, undefined];

    return ['1', 0];
}

let [ruleName, ruleIndex] = ruleFromPosition(0);
like image 130
SVSchmidt Avatar answered Oct 29 '22 19:10

SVSchmidt