Utilizing Object.fromEntries in Typescript

I am attempting to define a type called ObjectFromEntries that functions similarly to the return type of the Object.fromEntries function. Here is what I have so far:

type ObjectFromEntries<Entries extends [keyof any, any][]> = { [key in Entries[number][0]]: ___ };

declare var z: ObjectFromEntries<[["a", number], ["b", string], ["c", Date]]>
z.a // expected: number
z.b // expected: string
z.c // expected: Date

However, I am unsure what to substitute for ___.

When I attempt to use

key extends Entries[infer I][0] ? Entries[I][1] : never
, I encounter an error:

Type 'I' cannot be used to index type 'Entries'.(2536)
Type '0' cannot be used to index type 'Entries[I]'.(2536)

If I try Entries[number][1], every property ends up with the type string | number | Date, which makes sense but is not ideal.

How can I effectively synchronize key with the index to obtain the correct type?

Answer №1

If you want to express it differently, you could try this approach:

type ObjectFromEntries<Entries extends [keyof any, any][]> = {
    [K in Entries[number][0]]: Extract<Entries[number], [K, any]>[1]
} 

declare var x: ObjectFromEntries<[["a", number], ["b", string], ["c", Date]]>
x.a.toFixed();
x.b.toUpperCase();
x.c.getFullYear();

Just a suggestion, you can also simplify the code like so:

type ObjectFromEntrySet<E extends [keyof any, any]> = {
    [K in E[0]]: Extract<E, [K, any]>[1]
}

declare var y: ObjectFromEntrySet<["a", number] | ["b", string] | ["c", Date]>
y.a.toFixed();
y.b.toUpperCase();
y.c.getFullYear();

I hope this alternative explanation helps you with your task.

Check out the code on the TypeScript Playground here

Answer №2

In order to achieve this, simply include

"lib": ["ES2019"]
within the configuration file tsconfig.json:

{
  "compilerOptions": {
    "lib": ["ES2019"]
  }
}

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

Using TypeScript, extract the value of a Promise from a Page Object

Struggling to retrieve a value from a WebDriver promise in a Protractor solution using TypeScript, the response keeps coming back as undefined. get nameInput(): string { var value: string; this.nameElement.getAttribute('value').then(v =& ...

Error encountered in Angular build optimization process: TypeError - the function this._createContainer is not recognized

When compiling an Angular 7.2.5 application with --prod, a strange run-time error occurs. The stack trace shows: ERROR TypeError: this._createContainer is not a function at bg.pa (Viewer.js.pre-build-optimizer.js:143) at new bg (Modeler.js.pre-bu ...

The hierarchy of precedence when using the TypeScript Type Assertion operator

Is it necessary to wrap the js-ternary operator with 'as' Type Assertion? ios ? TouchableOpacity : View as React.ElementType Will it automatically use the result of '?:' since it comes first? Or would a better implementation be: (ios ...

Angular 2: Implementing functionality on selected option

I have written code for my HTML <select [(ngModel)]="empfile.storeno" class="form-control"> <option *ngFor="let p of concept" [ngValue]="p.MAP_Code">{{p.MAP_Code}}</option> </select> As for my component public concept = []; ...

After subscribing, creating the form results in receiving an error message that says "formgroup instance expected."

I am currently working on a project using Angular 6 to create a web page that includes a form with a dropdown menu for selecting projects. The dropdown menu is populated by data fetched from a REST API call. Surprisingly, everything works perfectly when I ...

The flow union type operates smoothly without any errors occurring

In the code snippet below, I have defined a type 'Something' which can have three possible values: 'A', 'B', or 'C'. The function 'f' takes an object of type Something as input and returns a string based on ...

Typescript: It is possible that the object is 'undefined' only for the '<' and '>' operators

I've been encountering a very peculiar issue with the error message Object is possibly 'undefined'. My objective is to create a condition similar to this: if (productPages?.length && productPages[productPages.length - 1].docs?.length < 1 ...

I am looking for a guideline that permits me to restrict the use of a form validation tool

We have developed our own version of the Validators.required form-validator that comes with Angular 7, but now we need to switch to using CustomValidators.required. To enforce this change, we are considering banning the use of the old Validators.required b ...

Hand over the component method as an argument to a class

One of my components, called First, is responsible for creating a new instance of a Worker class. During the creation process of this class, I intend to pass the Read method as a callback method. Once this class completes its task, it will then invoke thi ...

When working with Angular 2, it is important to note that the NgFor directive only supports binding to Iterables like Arrays. If you encounter an error message stating "Cannot find a differ supporting object '[object Object]' of type 'leaveType

After an extensive search and exploration for a solution to my problem, I found one, but unfortunately it didn't work as expected. The issue at hand involves displaying static data/list in dropdown options using TypeScript. Currently, I am working wit ...

What is the best technique for verifying the existence of data in the database before making updates or additions with Angular's observables?

I am facing a straightforward issue that I need help with in terms of using observables effectively. My goal is to search my database for a specific property value, and if it exists, update it with new data. If it does not exist, then I want to add the new ...

Images in the Ionic app are failing to display certain asset files

Currently, I am working on an Ionic 4 app for both Android and iOS platforms. The issue I am facing is that only SVG format images are displaying in the slide menu, even though I have images in both SVG and PNG formats. public appPages = [ { ...

Is it possible to use a TypeScript Angular (click) event with an object property as the value?

Seeking assistance in creating a dynamic error card featuring various error messages along with a retry button. Below is a snippet from my TypeScript object: errorCard: any = []; if(error) { this.errorCard.errorMessage = "Oops, please try again"; ...

Elevating Material-UI Drawer using makeStyles to a whole new level with styled-components

Currently working on a React app using TypeScript, Material-UI, and styled-components. While incorporating a SideDrawer with Material-UI Drawer component, I am transitioning my code from makeStyles to styled-components for easier maintenance. How ...

Update all occurrences of a particular value to null within the Realtime Database using Firebase Cloud Functions

I need to update the values of a specific userID linked to multiple post keys in my database by setting the userID to null. The userIDs are associated with post keys located in the path: posts/ivies/userIDs in my database. Take a look at how the database i ...

How to dynamically insert variables into a separate HTML file while creating a VS Code extension

Currently working on a vscode extension, I'm facing an issue with containing the html in a string (like this: https://github.com/microsoft/vscode-extension-samples/blob/main/webview-view-sample/src/extension.ts). It leads to a large file size and lack ...

Dynamic loading of locale in Angular 5 using Angular CLI

Angular 5 offers a solution for loading i18n locale dynamically using registerLocaleData https://angular.io/guide/i18n#i18n-pipes I am interested in loading the locale based on a dynamic setting, such as one stored in localStorage. I tested loading a sin ...

Is there a way to ensure that the content of my modal dialog only displays once when it is opened?

While working with Chakra UI, I encountered a unique issue that I hadn't faced before with Material UI. The problem arises when using the Chakra UI modal dialog - all components inside it get rendered twice upon opening. Despite attempting to disable ...

Set a generic function type to a variable

Currently, I am facing an issue where I have a declared function type with generics that I want to assign to a named arrow function. Below is an example of the code: import { AutocompleteProps } from '@material-ui/lab/Autocomplete'; const itemTo ...

Ways to effectively utilize an interface incorporating props.children and other property varieties

Currently working on a project with Next.js and Typescript. In order to create a layout component, I defined the following interface: export interface AuxProps { children: React.ReactNode; pageTitle: 'string'; } The layout component code sn ...