Match values from an array to a universal type in Typescript

I am currently working on developing a function in Typescript that maps an array of string values to a generic type. Each value in the array corresponds to a key in the object with the same index. For example:

Let's consider an interface called Person

interface Person {
    lastName: string;
    firstName: string;
}

We have an array of values

const values = ['foo', 'bar']

The expected outcome is an instance of Person

{
    lastName: 'foo',
    firstName: 'bar'
}

This function should be designed like this

const parse = <T extends Record<string, string | undefined>>(values: Array<string | undefined>)<T> => {
  ...
}

const result: Person = parse(['foo', 'bar']);

Merging 2 arrays into one object is not challenging, but defining the type for the returned generic can simplify things. Methods like Object.keys(T) or for key in T do not work well for obtaining the index of a key.

You can provide a generic with 100 properties and an array with only 5 values, where the first 5 properties will be assigned while the rest are null or undefined. Similarly, you can pass a generic with 3 properties and an array with 100 values, with only the initial 3 values being utilized. The array may include undefined or null

Answer №1

Remember that when your code is compiled, all information regarding data types is lost. Therefore, during runtime, your function will not have any knowledge of the Person object or its properties.

In order to write a function that requires information about the returned object, consider defining a class instead of an interface and including a parameter in your function that accepts a constructor.

class Person {
    lastName = ""
    firstName = ""
}

type Constructor<T> = { new(): T }

function parse<T>(constructor: Constructor<T>, values: unknown[]): T {
    const obj = new constructor()
    // you can now use Object.keys(obj) and similar methods
    // ...
}

const result = parse(Person, ['foo', 'bar'])

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

You can't observe the behavior of simulated functions in a class with a manually created mock

Kindly note that I have set up a comprehensive Github repository where you can download and explore the content yourself here I am currently working on mocking a non-default exported class within a module using a manual mock placed in the folder __mocks__ ...

Choose does not showcase the updated value

My form contains a form control for currency selection Each currency object has the properties {id: string; symbol: string}; Upon initialization, the currency select component loops through an array of currencies; After meeting a specific condition, I need ...

The functions Lodash includes for checking undefined and null values

Utilizing Lodash's isUndefined and isNull methods can be quite handy. For instance, if you have a number variable that needs to be checked for existence before using it, you could approach it like this: someNumber:number; ...... if (_.isUndefined(so ...

In what situations might a finally block fail to execute?

Are there any circumstances where the code in a finally block may not be reached, aside from the usual suspects like process exit(), termination signal, or hardware failures? In this TypeScript code snippet that usually runs smoothly in node.js, occasiona ...

What is the best way to call a method from app.component in another component?

Having recently delved into Typescript and Angular 2, I've been struggling to find a solution online that fits my needs. Let's consider the example of an app.component: export class AppComponent implements OnInit { constructor(public _test ...

Is it possible for TypeScript to convert objects while preserving type annotations?

Apologies for my limited English skills, but I will do my best to explain my dilemma. I am looking to create a TypeScript function that can replace the keys of an Object. For example: interface Target { name: string; ID: number; } // The functio ...

Why is Sentry choosing to overlook certain errors in my React application?

While using Sentry to catch errors in my React app, I discovered that it ignores errors with 502 and 504 HTTP codes as well as some React errors. I am unsure why this is happening and would like to modify this behavior. Below is the initialization functio ...

Ionic - What is the correct way to import ViewController? - Uncaught (in promise): Error: ViewController provider not found

I have a Popover in my app and I want it to behave differently based on the selected item. I followed the instructions in the Ionic documentation to achieve this. Error: Uncaught (in promise): Error: No provider for ViewController! When I tried adding ...

The TypeScript extension of a type from an npm package is malfunctioning

I am utilizing the ws package to handle WebSockets in my Node.js project. I aim to include a unique isHealthy attribute to the WebSocket class. The approach I have taken is as follows: // globals.d.ts import "ws" declare module "ws" { ...

Rearrange an element in an array from last to first position using typescript

I am working with an array that looks like this var column = ["generic complaint", "epidemic complaint", "epidemic1 complaint", "epidemic2 complaint", "bal vivah", "name"] My goal is to move the last element of the array to the first position, resultin ...

What is the best way to create a T-shaped hitbox for an umbrella?

I've recently dived into learning Phaser 3.60, but I've hit a roadblock. I'm struggling to set up the hitbox for my raindrop and umbrella interaction. What I'd love to achieve is having raindrops fall from the top down and when they tou ...

Using React.PureComponent, the list component efficiently renders each item with optimized performance

We've developed a reusable list component in ReactJS. To address performance concerns, we decided to incorporate the shouldComponentUpdate method to dictate when our list component should re-render. public shouldComponentUpdate(nextProps: TreeItemInt ...

Encountered an issue while trying to assign a value to the 'value' property on an 'HTMLInputElement' within a reactive form

When I upload a picture as a data record, the image is sent to a server folder and its name is stored in the database. For this editing form, I retrieve the file name from the server and need to populate <input type="file"> in Angular 6 using reacti ...

Tips for stopping TypeScript from halting Webpack compilation due to undefined variables stated in Webpack's ProvidePlugin

Is there a way to prevent WebPack's build process from failing when the TypeScript compiler throws errors about unresolved variables that are already configured in Webpack's ProvidePlugin settings? webpack.config.js plugins: [ ... new webpack.P ...

Absolute file path reference in Node.js

I'm working on a Node.js project using WebStorm IDE. Here's the structure of my project: The root folder is named "root" and inside are 2 folders: "main" and "typings". The "main" folder has a file called "foo.ts", while the "typings" folder co ...

Troubleshooting an issue with a Typescript React component that is generating an error when using

I am in the process of implementing unit testing in a Typescript and React application. To start off, I have created a very basic component for simplicity's sake. import React from "react"; import ReactDOM from "react-dom"; type T ...

This TypeScript error occurs when trying to assign a value of type 'null' to a parameter that expects a type of 'Error | PromiseLike<Error | undefined> | undefined'

Currently, I am making use of the Mobx Persist Store plugin which allows me to store MobX Store data locally. Although the documentation does not provide a TypeScript version, I made modifications to 2 lines of code (one in the readStore function and anot ...

Calculating different percentages from a reduced map containing JSON data

Forgive me in advance if there's a similar question out there, but after a day of searching, I couldn't find what I need. I'm calling an API that responds with data, and I've extracted the necessary details to create a JSON file with t ...

Retrieve the accurate file name and line number from the stack: Error object in a JavaScript React Typescript application

My React application with TypeScript is currently running on localhost. I have implemented a try...catch block in my code to handle errors thrown by child components. I am trying to display the source of the error (such as file name, method, line number, ...

Is it Observable or Not? Typescript Typehint helping you determine

I'm facing an issue while writing a function with correct typehints. It seems to work fine with explicit type hinting but breaks down when trying to use automatic type hinting. Can someone please help me identify the error in my code and suggest how I ...