I am looking to generate an array with key-value pairs from an object that will be seen in the examination

I have a task that involves configuring a table and creating objects with key-value pairs for each key.

 type KeyValuePair<T> = {/** ... */};
let userKeyValuePair :KeyValuePair<{id:number,userName:string}>;
 // => {key:'id',value: number} or {key: 'userName', value: string}

userKeyValuePair = {key: 'id' /** with autocomplete */ , value: 'string'}; // will result in an error
userKeyValuePair = {key: 'id' ,value: 687 /** any number */}; // will work correctly

Answer №1

Here's a solution that may fit your needs:

type KeyValuePair<T> = {
  [K in keyof T]-?: { key: K, value: T[K] }
}[keyof T];

This code defines a mapped type that generates an object type for each key, such as {a: string, b: number} transforming into

{a: {key: "a", value: string}, b: {key: "b", value: number}}
. By indexing with the keys, we create a union of property types like
{key: "a", value: string} | {key: "b", value: number}
.

For example:

type Show = KeyValuePair<{ id: number, userName: string }>;
/* type Show = {
    key: "id";
    value: number;
} | {
    key: "userName";
    value: string;
} */

You can apply this to your case as well:

let userKeyValuePair: KeyValuePair<{ id: number, userName: string }>;

userKeyValuePair = { key: 'id' /** with autocomplete */, value: 'string' }; // error
userKeyValuePair = { key: 'id', value: 687 /** any number */ }; // okay

Seems to work fine.

Link to Playground

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

Utilize ngx-filter-pipe to Streamline Filtering of Multiple Values

Need assistance with filtering an array using ngx-filter-pipe. I have managed to filter based on a single value condition, but I am unsure how to filter based on multiple values in an array. Any guidance would be appreciated. Angular <input type="text ...

What is the best approach to organize data from an observable based on a nested key?

I'm currently developing a new application and struggling with grouping data. The data is being pulled from an observable, and I need to group objects by their status and push them into an array. I attempted to use the groupBy() method, but unfortunat ...

Workspace watch mode does not update Typescript definitions

Greetings to all who are reading this, I have created a React micro-frontend project using SPA v5.9, Webpack v5.75, Babel-loader v9.1, Ts-loader v9.4, and Yarn workspace v3.5. The project structure is very basic: Root SPA => Package Root Application S ...

What could be causing my Vue code to behave differently than anticipated?

There are a pair of components within the div. When both components are rendered together, clicking the button switches properly. However, when only one component is rendered, the switch behaves abnormally. Below is the code snippet: Base.vue <templa ...

Having trouble retrieving the user-object within tRPC createContext using express

I'm encountering an issue with my tRPC configuration where it is unable to access the express session on the request object. Currently, I am implementing passport.js with Google and Facebook providers. Whenever I make a request to a regular HTTP rout ...

A TypeScript interface or class

Just had a lively discussion with a coworker and wanted to get some clarification. When shaping an object in TS, should we use a class or an interface? If I need to ensure that a function returns an object of a specific type, which one is the best choice? ...

What could be causing this peculiar behavior in my React/TypeScript/MUI Dialog?

My React/TypeScript/MUI application has a dialog that displays multiple buttons. Each time a button is clicked, the dialog function adds the button value to a state array and removes it from the dialog. Although it seems to be working, there is an issue wh ...

Comparing Input and Output Event Binding

Can you provide reasons why using @Output for events is more advantageous than passing an @Input function in Angular 2+? Utilizing @Input: Parent Template: <my-component [customEventFunction]=myFunction></my-component> Inside parent-compone ...

Enhancing JavaScript functions with type definitions

I have successfully implemented this TypeScript code: import ytdl from 'react-native-ytdl'; type DirectLink = { url: string; headers: any[]; }; type VideoFormat = { itag: number; url: string; width: number; height: number; }; type ...

An error occurs when attempting to access a property that does not exist on type 'never'. Why is this considered an error rather than a warning?

I am experiencing an issue with the following code snippet: let count: number | undefined | null = 10; count = null; let result: string | undefined | null = count?.toFixed(2); console.log(`Result: ${result}`); The error message I received is as follows: ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...

How can I retrieve a certain type of object property in TypeScript?

Imagine having a collection of flags stored in an object like the example below: type Flags = { flag1: string, flag2: string, flag3: boolean, flag4: number } // const myFlags: Flags = { // flag1: 'value 1', // flag2: 'value 1&ap ...

Tips for displaying HTML content dynamically in React using TypeScript after setting a stateVariable

To render an HTML block after successfully setting a state variable, I have defined my state variables and functions below. The code snippet is as follows: const formService = new FormService(); const [appointmentDate, setAppointmentDate] = us ...

The variable <variable> is not meeting the 'never' constraint. Error code: ts(2344)

Currently, I am attempting to utilize Supabase alongside TypeScript. However, I encounter an error when trying to use functions like insert(), update(), upsert(), etc. Specifically, the issue arises when declaring the object I want to declare: "Type & ...

Leveraging a returned value from a function in Typescript within a React component

I am currently facing a challenge where I need to extract values from a Typescript function and use them to dynamically render a React page. Specifically, the two values I am working with are the outputs of getIcon() and getSpaces(). This is how I attempt ...

Creating two number-like types in TypeScript that are incompatible with each other can be achieved by defining two

I've been grappling with the challenge of establishing two number-like/integer types in TypeScript that are mutually incompatible. For instance, consider the following code snippet where height and weight are both represented as number-like types. Ho ...

Moving from Http to HttpClient in Angular4Changeover your Angular4

I recently migrated my Angular app to use the new HttpClient, but I'm encountering some challenges in achieving the same results as before with Http. Can anyone help me out? Here's what I was doing with Http: getAll() { return this.http.get ...

Is it possible for me to create a union type that connects parameters and responses in a cohesive manner

I'm interested in creating a custom type that functions can use to indicate to callers that an input parameter of a specific type corresponds to a certain output type. For instance, consider the following scenario: type ResponseMap = { requestPath: ...

How can I determine the data type of an Array element contained within an Interface member?

Is there a way to extract the type of key3 in MyInterface2 and use it in key3Value, similar to key2Value? interface MyInterface { key1: { key2: string } } const key2Value: MyInterface['key1']['key2'] = 'Hi' / ...

Exploring the utilization of an interface or class in Typescript

Imagine a common situation where users need to provide an email and password for logging in using Typescript. To make this process more organized, I want to define a strong type that represents the user's login information and send it securely to the ...