@types - converting an array of values into object keys

If I have an array of strings like this:

const arr = ["a", "b", "c"];

How can I convert it into an object where these values become keys?

const obj = {
 a: "can be anything",
 b: 2,
 c: 0
}

I attempted to use

type TupleToObject<T extends readonly string[]> = {
    [P in T[number]]: any;
};

but it doesn't appear to be strongly typed.

Answer №1

To utilize the as const TypeScript syntax effectively, you can refer to the documentation here.

const arr = ["a", "b", "c"] as const;
// inferred type: readonly ["a", "b", "c"]


type TupleToObject<T extends readonly string[]> = {
    [P in T[number]]: any;
};

type MyObject = TupleToObject<typeof arr>
// type MyObject = {
//     a: any;
//     b: any;
//     c: any;
// }

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

Vue HeadlessUI Error: The function vue.defineComponent is not recognized

Trying to incorporate @headlessui/vue into my nuxt project has been a challenge. My attempt at using it looks like this: <template> <Menu> <MenuItems> <MenuItem>Item</MenuItem> </MenuItems> </Menu&g ...

Erase the destination pin on Google Maps

I am currently working on a project that involves displaying hit markers on google maps along with a route from start to finish. Although I have successfully displayed the route, I encountered an issue where both the origin and destination have identical ...

The Next.js build failed due to the absence of the required "slug" parameter being passed as a string

I'm currently working on setting up a blog using Next.js and TypeScript, and I've encountered an issue with [slug].tsx. The error message I'm receiving is: Build error occurred Error: A required parameter (slug) was not provided as a strin ...

The LOCK is defined as an ENUM and Interface in the sequelize library, specifically in the types/transaction.d.ts file

Utilizing TypeScript for my Node.js server and connecting to a MySQL database with the help of sequelize. Everything runs smoothly when I execute nodemon server.ts. However, running npx tsc throws the following error: node_modules/sequelize/types/transact ...

Challenges with exporting dynamically generated divs using jspdf in an Angular 2 project

I have been utilizing the jspdf library to print div elements in my current project. But I recently discovered an issue where dynamic content within a div is not being printed correctly. Specifically, when incorporating simple Angular if statements, jspdf ...

What is the reason behind TypeScript creating an IIFE for a class declaration?

Upon reviewing this TypeScript code: class Greeter { greet() {} } An IIFE (Immediately-Invoked Function Expression) is created around the constructor function and all prototype function declarations as shown below: var Greeter = (function () { f ...

Dynamically insert an element using RouterLink

In my Angular component, I have successfully added an anchor element like this: <a [routerLink]="['/LoggedIn/Profile']">Static Link</a> Clicking the link navigates to the desired component without any issues. Now, I want t ...

Enhance your material-ui component using TypeScript functionality

Exploring ways to enhance the Material-ui Button component by introducing new props. The objective is to introduce a new prop called fontSize with three size options - small, medium, large. <Button variant="outlined" color="primary" ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

What are the consequences of relying too heavily on deep type inference in React and Typescript?

In the process of migrating my React + Javascript project to Typescript, I am faced with preserving a nice unidirectional flow in my existing code. The current flow is structured as follows: 1. Component: FoobarListComponent -> useQueryFetchFoobars() 2 ...

"An import error occurred in 'node_modules/rxjs/Rx' as it does not have a member named 'Rx' available for export

What could be causing the issue with importing rxjs/Rx? I am currently using VS code version 1.14.1. The following imports work: import * as Rx from 'rxjs/Rx'; as well as import Rx from 'rxjs/Rx'; However, this import does not work ...

Angular's HttpClient.get method seems to have trouble retrieving real-time data from a Firebase database

I have been debugging and I suspect that the error lies in this part of the code. The DataService class's cargarPersonas function returns an Observable object, but I am struggling to understand how to properly retrieve the database data and display it ...

Storing checkbox status in Angular 7 with local storage

I am looking for a way to keep checkboxes checked even after the page is refreshed. My current approach involves storing the checked values in local storage, but I am unsure of how to maintain the checkbox status in angular 7 .html <div *ngFor="let i ...

What is the best way to perform unit testing on a function component that includes React.useState() using jest and enzyme?

I'm working on a function component that utilizes React.useState() to handle the state of a drawer modal. My challenge lies in testing this function and its ability to modify state using jest enzyme, as I cannot access its state function due to it not ...

Execute service operations simultaneously and set the results in the sequence they are received

I am faced with a challenge involving multiple service methods that fetch data from various servers. The responses from these APIs come in at different times, and I need to store the responses in variables as soon as they are received. Here are my service ...

Keep the list up-to-date by adding new items promptly

Utilizing Angular 7, I have implemented the following service (Click here for StackBlitz Example): @Injectable({ providedIn: 'root' }) export class TodoService { todos: BehaviorSubject<Todo[]> = new BehaviorSubject([ { id: 1, tit ...

What are the steps to retrieve the original source code of an HTML file, specifically in Angular 2 RC4

Is there a way to retrieve the source code that I manually typed in my IDE using JavaScript? Note: I am working with angular2 rc4. I attempted to access it using Reflect.getMetadata, but encountered errors indicating that it is not functioning properly. ...

Struggling to fetch a DropDown menu from an Array in ReactJS

Trying to utilize an array of City Names in a Auto Complete text field within ReactJS. The array is successfully printed, but encountering difficulty displaying the list in the browser's Dropdown. An error message is being displayed in the browser r ...

When including the JQuery definition in a TypeScript code, it is not being included in the transcompiled JavaScript file as expected

After learning about importing TypeScript libraries and their compilation to JS for build output, I encountered a script that did not behave as expected. The issue remains unclear. main.ts /// <reference path="../typings/globals/jquery/index.d.ts" /&g ...

The error message "TypeError: text is not a function" is displayed when trying to utilize the text() method from either Blob

My current dilemma revolves around the usage of functions defined in the typescript lib.dom.d.ts file within my node.js express backend that is implemented using TypeScript. Specifically, I am encountering issues with the File/Blob interfaces where a File ...