TypeScript combines strong typing for arrays into a unified array of objects

I developed a JavaScript function that can merge multiple arrays into an array of objects based on provided key names. Here’s an example:

const mergeArraysToSeries = (arrs, keys) => {
  const merged = [];

  for (let dataIndex = 0; dataIndex < arrs[0].length; dataIndex++) {
    const el = keys.reduce((combined, currKey, keyIndex) => {
      const val = arrs[keyIndex][dataIndex];
      return { ...combined, [currKey]: val };
    }, {});
  
    merged.push(el);
  }

  return merged;
}

const example = mergeArraysToSeries([[1,2,3], ['a','b','c']], ['num', 'letter'])
// example = [{num: 1, letter: 'a'}, {num: 2, letter: 'b'}, {num: 3, letter: 'c'}] 

I am now looking to enhance this function with TypeScript to achieve autocomplete on the merged array and ensure type safety for each key. Is there a way to accomplish this without relying on any types?

The current type signature I have is:

const mergeArrayToSeries = <K>(arrs: any[][], keys: (keyof K)[]): Record<keyof K, any>[] => ...

I would like to eliminate the usage of any for passed arrays while maintaining type safety. Any suggestions on how to achieve this?

Thank you!

Edit: The goal is to make this work seamlessly for merging any number of arrays together.

Answer №1

If you're looking to combine arrays into a series, you can employ a function like the one below:

declare function mergeArraysToSeries<
  T extends any[],
  U extends any[],
  P1 extends string,
  P2 extends string
>(arrays: [T, U], properties: [P1, P2]): {
    [K in P1]: T[number]
  } & {
    [K in P2]: U[number]
  }[];

const example = mergeArraysToSeries([[1,2,3], ['a','b','c']], ['num', 'letter']); // example is { num: number; letter: string }[]

Playground link

Additional Information

To accommodate more than two arrays, you can include additional overloads as shown below.

declare function mergeArraysToSeries<T, U, P extends readonly string[]>(arrays: [T[], U[]], properties: P): { [K in P[0]]: T } & { [K in P[1]]: U }[]
declare function mergeArraysToSeries<T, U, V, P extends readonly string[]>(arrays: [T[], U[], V[]], properties: P): { [K in P[0]]: T } & { [K in P[1]]: U } & { [K in P[2]]: V }[]
declare function mergeArraysToSeries<T, U, V, W, P extends readonly string[]>(arrays: [T[], U[], V[], W[]], properties: P): { [K in P[0]]: T } & { [K in P[1]]: U } & { [K in P[2]]: V } & { [K in P[3]]: W }[]

const two = mergeArraysToSeries([[1, 2, 3], ['a', 'b', 'c']], ['num', 'letter'] as const)
const three = mergeArraysToSeries([[1, 2, 3], ['a', 'b', 'c'], ['foo', 'bar', 'baz']], ['num', 'letter', 'other'] as const)
const four = mergeArraysToSeries([[1, 2, 3], ['a', 'b', 'c'], ['foo', 'bar', 'baz'], [0, 0, 0]], ['num', 'letter', 'other', 'index'] as const)

Playground link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...

What is the best way to merge imported types from a relative path?

In my TypeScript project, I am utilizing custom typings by importing them into my .ts modules with the following import statement: import { MyCoolInterface } from './types' However, when I compile my project using tsc, I encounter an issue wher ...

Is there a way to retrieve a compilation of custom directives that have been implemented on the Vue 3 component?

Is there a way to retrieve the list of custom directives applied to a component? When using the getCurrentInstance method, the directives property is null for the current component. I was expecting to see 'highlight' listed. How can I access the ...

Inquiring about Vue 3 with TypeScript and Enhancing Types for Compatibility with Plugins

I've been struggling to find a working example of how to implement type augmentation with Vue3 and TypeScript. I have searched for hours without success, trying to adapt the Vue2 documentation for Vue3. It appears that the Vue object in the vue-class ...

Choose the Angular 2 option

I am having an issue with the select option in my code. The person's gender property is assigned 'M' for male, but I need to allow users to change it to 'F' for female. Here is the HTML code snippet: <span > <span &g ...

Using TypeScript with knockout for custom binding efforts

I am in the process of developing a TypeScript class that will handle all bindings using Knockout's mechanisms. Although I have made progress with the initial steps, I have encountered a roadblock. While I can successfully bind data to my HTML element ...

Sending information to components in Angular using Router

Should I pass data through the angular router to a component, or is it better to use a service? Currently, the component is receiving data in the following way: this.account = activatedRoute.snapshot.data.account ...

Error: React is throwing a SyntaxError because a ")" is missing in the argument list

While working on a React-typescript project using Vite, I encountered an issue where my page was displaying blank and showing the error : Uncaught SyntaxError: missing ) after argument list (at main.tsx:6:51) This error was found in the main.tsx file : im ...

What steps should I take to fix the SyntaxError occurring with the unexpected token 'export' in a React Next.js project?

Currently working on a React Next.js project and I've come across an unexpected SyntaxError: Unexpected token 'export' issue. I've reviewed the solutions provided here, but I'm having trouble grasping how to correctly implement th ...

Unable to locate the next/google/font module in my Typescript project

Issue With Import Syntax for Font Types The documentation here provides an example: import { <font-name> } from 'next/google/font'; This code compiles successfully, but throws a "module not found" error at runtime. However, in this disc ...

Easy steps for importing node modules in TypeScript

I'm currently navigating the world of TypeScript and attempting to incorporate a module that is imported from a node module. I have chosen not to utilize webpack or any other build tools in order to maintain simplicity and clarity. Here is the struct ...

Transforming Javascript into Typescript with node modules in Visual Studio 2015

After developing a JavaScript web app using npm and webpack, I successfully converted all the .js files to .ts using the PowerShell command found here. Now, I am looking to transition to a VS2015 TypeScript project but struggling to find guidance on how ...

I am struggling to make the map method display the specific components I need

Attempting to create a scalable Custom Form using an array of objects and a custom Input field in a React-Typescript project import React, { ChangeEvent } from "react" import { InputField } from "./InputField" interface FormItem { ...

Executing multiple HTTP requests in Angular using the HttpClient

Recently, I came across a concerning issue in my Angular 5 App. It all started with this simple call in my service: interface U{ name:string; } ... constructor(private http : *Http*, private httpC:HttpClient) // Http is deprecated - its a compare test ...

Tips for handling user click events in Angular 2?

In Angular2, I am facing an issue with two components. When a user clicks a button in component1, a method is triggered that stores data in the shared service to a variable. However, component2's ngOnInit() method initializes this variable to undefine ...

...additional properties in React function components using TypeScript

Here is a snippet of code that I am working with: <InputComponent id="email" name={formik.values.email} type="text" formik={formik} className="signInInput" disabled/> However, there seems to be an issue with the disable ...

Beginner - managing tasks with React and TypeScript

Can someone assist me with a minor issue? I have experience programming in React using pure JavaScript, but I'm struggling with transitioning to TypeScript. I don't quite understand all the hype around it and am finding it difficult to work with. ...

What is the best way to invoke a function in a React component from another component?

I am working with a component structure that includes the Input component. In this component, there is a function called validate that is triggered by the onChange event. Here is a snippet of the code: import React, {FC, useState} from 'react'; ...

The issue with IONIC/Angular lies in its inability to properly render the JSON data retrieved

I have recently started learning IONIC/Angular and Javascript, although I do have some background in other programming languages. The issue I'm currently facing is related to fetching JSON data from an external API (I've created the API with Stra ...

Access Element in Array by Type using TypeScript

Within a TypeScript project, there exists an array of containers that possess a type attribute along with supplementary data based on their individual types. type Container<Type extends string> = { type: Type; } type AContainer = Container<" ...