Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
Typescript: simpler way to type object to array transformation

I'm converting certain properties from an object to an array.

const result = ({ a, b }: { a: string, b: number }) => [a, b]; // (string | number)[]

However, the standard way always returns an insufficient typescript type (string | number)[]

I have to always specify my output type for it to correctly type the result.

const result = ({ a, b }: { a: string, b: number }): [string, number] => [a, b]; // [string, number]

Is there a simpler way?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Just add as const after the array is created - this is called a const assertion. It indicates that the newly created array is actually a tuple, which it has to be if you're going to count on it having 2 elements where the first is a string and the second is a number.

// readonly [string, number]
const result = ({ a, b }: { a: string, b: number }) => [a, b] as const; 

The only difference between this and the example in your original question is that resulting type will be readonly. There will be no way to alter the value of result unless you do a specific assertion that would allow this.

about 4 years ago · Juan Pablo Isaza Report

0

There's no getting away from the fact that you have to add a little bit of verbosity to get a tuple type back. You can create a helper function which generates tuple types from array literals - whether it is preferable to declaring const or the return signature directly is up to you:

const asTuple = <T extends [any, ...any]>(array: T) => array;

const objectToTuple = ({ a, b }: { a: string, b: number }) => asTuple([a, b]);

const result = objectToTuple({a: "a", b: 1}) // [string, number]
about 4 years ago · Juan Pablo Isaza Report

0

As far as I know, there isn't.

You can do [a, b] as [string, number] but that's basically the same verbosity. Another alternative is giving result a function type, but that's just moving the "problem" here.

Besides, adding that small return type declaration isn't that bad. There isn't much else TS can do, as it can't assume you want a [string, number] by default. That would be far from backwards compatible (or even desired by most people).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!