0

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!

2
  • 3
    Your second option works (typescriptlang.org/play?#code/…) The other version would be a as const: typescriptlang.org/play?#code/… Commented Nov 24, 2021 at 19:02
  • Please consider reviewing the guidelines for How to Ask and what constitutes a minimal reproducible example. When you show code and something is not working about it, it doesn't help to just say "but it didn't work". It is expected that you describe exactly what is not working... is there an error message? If so, what is it and where does it happen? Is there some unexpected output? What and where? Since the version you say "didn't work" actually does work in the TS Playground, right now the problem isn't reproducible and thus the question might be closed unless you rectify it. Good luck! Commented Nov 24, 2021 at 20:04

2 Answers 2

1

This can be achieved using as const.

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

const [active,status,numberEleven] = f();
const twelve = numberEleven + 1;
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.