Setting up the properties of an object directly from an array - all in one line

Here is my array:

const a = ['one', 'two'] as const;

Here is the type of object I'm working with:

type T = {
    { [key in typeof a[number]]: number;
}

The expected result should look like this:

const r: T = {
    one: 0,
    two: 0
}

However, when I tried to use a map function, it didn't work:

const z: T = a.map((prop) => [prop, 0]);

Instead of the desired output, I received an error message saying: Type '(number | "one" | "two")[][]' is missing the following properties from type 'T': one, two(2739)

Answer №1

Everything seemed fine up until the final step. I would suggest changing the last part to this:

const z: T = a.reduce((obj, prop) => ({...obj, [prop]: 0}), {} as T);

The 'a' array is being reduced into an object in this step, starting with an empty object of type T and then adding each property with a value of 0.

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

Export full module as a constructor function

Imagine having a nodejs module where requiring it gives you a constructor function. Here's an example: var Mod = require("modulename"); var mod = new Mod(); mod.method(); Now, I want to create a .d.ts declaration file that can be imported and utiliz ...

The optimal location to declare a constructor in Typescript

When it comes to adding properties in an Angular component, the placement of these properties in relation to the constructor function can be a topic of discussion. Is it best to declare them before or after the constructor? Which method is better - Method ...

Exploring the Module System of TypeScript

I am working with a TypeScript module structured like this: let function test(){ //... } export default test; My goal is for tsc to compile it in the following way: let function test(){ //... } module.exports = test; However, upon compilation, ...

Tips on converting a date string in the format 'dd/MM/yyyy' to a date type using TypeScript

I have attempted the following code in order to convert the date from 'yyyy-mm-dd' format to 'dd/MM/yyyy'. However, when I check the typeof() of the result, it shows that it is a string. Is there a method to convert it into only a date? ...

What is the method to retrieve a generic TypeScript type within a function's code block?

When attempting to utilize a generic type within a TypeScript function: const func: <T extends number>() => void = () => { const x: T = 1 } An error message is generated: Cannot find name 'T'. TS2304 69 | const func: <T e ...

Utilizing a foundational element to automatically unsubscribe from multiple observable subscriptions

Within our Angular application, we have implemented a unique concept using a Base Component to manage observable subscriptions throughout the entire app. When a component subscribes to an observable, it must extend the Base Component. This approach ensures ...

Can a TypeScript generator function be accurately typed with additional functionality?

Generator functions come with prototype properties that allow for the addition of behavior. The generated generators inherit this behavior. Unfortunately, TypeScript does not seem to recognize this feature, leaving me unsure of how to make it aware. For i ...

Tips for triggering an error using promise.all in the absence of any returned data?

I'm dealing with an issue in my project where I need to handle errors if the API response returns no data. How can I accomplish this using Promise.all? export const fruitsColor = async () : Promise => { const response = await fetch(`....`); if( ...

TypeScript: Defining an Array Type within a Namespace or Module

Within a specific namespace, I have the following code: const operation1 = Symbol("operation1"); const operation2 = Symbol("operation2"); export interface Array<T> extends IConjable<T>, ISeqable<T> {} Array.prototype[op ...

Accurately locate all ChildComponents throughout the entire Component hierarchy

I am facing a challenge in Angular where I need to retrieve all the ChildComponents from my ParentComponent. The issue is that the ChildComponents are not directly nested within the ParentComponent, but instead they are children of other components which a ...

Having trouble running Jest tests with three objects in my Vite Vue TypeScript project

Here is a snippet of code that I am testing: import {Line} from "../src/modules/objs/line"; import {SceneWrapper} from "../src/modules/scene/sceneWrapper"; import * as THREE from "three"; import {Dr ...

Injecting Variables Into User-Defined Button

Presenting a custom button with the following code snippet: export default function CustomButton(isValid: any, email: any) { return ( <Button type="submit" disabled={!isValid || !email} style={{ ...

The length of video files created by MediaRecorder is not retained

This component prompts the user for camera access, displays a video preview, and allows the user to watch it again with video controls such as downloading or navigating to specific moments. However, there is an issue where the recorded video seems to be ...

syncfusion export pdf demonstrating the toggle button's current state

Currently, I am using syncfusion for converting my page to PDF format. I have a toggle button that is default set to true. However, regardless of the actual state of the toggle button, it always appears as on (true) when exported to PDF. I attempted to s ...

The sequence of execution in React hooks with Typescript

I'm having difficulty implementing a language switching feature. On the home page of my app located at /, it should retrieve a previously set preference from localStorage called 'preferredLanguage'. If no preference is found, it should defau ...

Attempting to implement a typeguard in Typescript that relies on the presence of specific content within an element

Currently, I am attempting to develop a Typescript conditional that verifies if a particular word is already present in the name. The function in question is as follows: isOrganic() { for (let i = 0; i < this.items.length; i++) { if(this.ite ...

Steps to develop a sub-route specifically for a single word

Take a look at this code: {path : 'recipes', component:RecipesComponent, children:[ {path:':id', component:RecipeDetailComponent}, {path:':new', component:NewRecipeComponent } ]}, No matter which link you use: h ...

Is it recommended to utilize the `never` type for a function that invokes `location.replace`?

I'm facing an issue with my TypeScript code snippet: function askLogin(): never { location.replace('/login'); } The TypeScript compiler is flagging an error: A function returning 'never' cannot have a reachable end point. Do ...

Unable to grab hold of specific child element within parent DOM element

Important Note: Due to the complexity of the issue, the code has been abstracted for better readability Consider a parent component structure like this: <child-component></child-component> <button (click)="doSomeClick()"> Do Some Click ...

Consecutive API requests within React context

When I'm developing locally, I encounter the error message Error: Rendered more hooks than during the previous render. in my application when refreshing the page. I suspect this is happening because I am making two calls within my provider. The first ...