chipimix
chipimix

Reputation: 290

How to destructure an array with elements of different types in typescript

The following code example works fine in javascript:

 const f = ()=> { return[true,"text",11]; }
 const [active,status,numberEleven] = f();
 const twelve = numberEleven + 1;

However, const twelve = numberEleven + 1; throws an error in typescript because numberEleven could be either a string, a boolean or a number:
I've tried to change the function return types:

const f = ()=> {
  const res: [boolean, string, number] = [true, warning, score];
  return res;
}

But it didn't work. I then tried to change the type of the deconstructed array like so:

 const [active,status,numberEleven]: [boolean, string, number] = f();

But this approach resulted in the following error:

Type '(string | number | boolean)[]' is not assignable to type '[boolean, string, number]'.
  Target requires 3 element(s) but source may have fewer.

So, what's the best way to destructure an array with elements of different types in typescript?
Thanks!

Upvotes: 0

Views: 739

Answers (2)

emeraldsanto
emeraldsanto

Reputation: 4741

This can be achieved using as const.

const f = () => {
  return [true, "text", 11] as const;
}

const [active,status,numberEleven] = f();
const twelve = numberEleven + 1;

Upvotes: 1

chipimix
chipimix

Reputation: 290

Indeed, the second option works. The error I shared was being caused by another block of code. thanks Dragomir! <3

Upvotes: 0

Related Questions