Converting the values from a string union type into keys for an object type mapping

Imagine you have a string union type called Fruit:

type Fruit = 'apple' | 'banana' | 'pear'

How can you create a type declaration to transform the above into an object type where these strings serve as keys (with their values also being strings)?

An example of how this manually defined type would look is:

type FruitObject = {
  apple: string;
  banana: string;
  pear: string;
}

Answer №1

If you want to create an object with predefined keys and value types, you can utilize the built-in type Record.

type Fruit = 'apple' | 'banana' | 'pear'

type FruitObject = Record<Fruit, string>
// {
//   apple:string;
//   banana:string;
//   pear:string;
//}

Try it out here!

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

What is the quickest way to send a message with just one press of the Enter key

Whenever I press "Enter Keyword," the message should be sent instead of going to the next line. ...

Struggling to understand the missing piece needed for properly importing into Angular modules. Any guidance would be appreciated

Is it advisable to include PrimeNg references in multiple modules or should they be centralized in a shared module? What is the recommended practice in this scenario? I am encountering issues with importing "p-dataTable" from primeng even though it is incl ...

There has been a mistake: "Unable to locate a suitable differ supporting object '[object Object]' of type 'object'. NgFor is only able to bind to Iterables like Arrays."

Currently facing an issue: I am trying to extract the values of "place" using ngFor directive. Here's what I have implemented: .html <ng-container *ngFor="let se of List" Here is the JSON data: .json "place": [ { &qu ...

We were caught off guard by the TypeScript error: an unexpected token showed up when we were expecting a constructor,

Trying to implement a function within a class in TypeScript. class Test { function add(x: number, y: number): number { return x + y; } } Encountering an error message stating: TypeScript Unexpected token, A constructor, method, access ...

Event triggered by an Angular counter

Typescript: countdown; counter = 10; tick = 1000; this.countdown = Observable.timer(0, this.tick) .take(this.counter) .map(() => --this.counter) Also in HTML: <div> <h1>Time Remaining</h1> <h2>{{countdow ...

What is the method for creating a new array of objects in Typescript with no initial elements?

After retrieving a collection of data documents, I am iterating through them to form an object named 'Item'; each Item comprises keys for 'amount' and 'id'. My goal is to add each created Item object to an array called ' ...

Unleashing the power of dynamic data imports in a Node.js application

My goal is to utilize the require function in a node/express application with typescript to import a json file. Here's how I attempted it: const url = `./data/${resource}.json`; const data = require(url); However, I encountered the error Cannot find ...

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...

What is the most effective method for locating and modifying the initial instance of an element within a group?

In my Javascript/Typescript collection, I have the following items: [ {"order":1,"step":"abc:","status":true}, {"order":2,"step":"xyz","status":true}, {"order":3,"step":"dec","status":false}, {"order":4,"step":"pqr","status":false}, {"order":5,"step":" ...

The real file that was brought in after indicating a module in the node_modules directory that was coded in Typescript

After creating a typescript module named moduleA, I am ready to publish this package and make it accessible from another typescript project. Currently, for testing purposes, I have installed 'moduleA' using 'npm install ../moduleA'. Th ...

Can [] be considered a valid type in Typescript language?

I've come across this function: function stringToArray(s: string|[]): [] { return typeof s === 'string' ? JSON.parse(s.replace(/'/g, '"')) : s; } This function is functioning as expected without any type warnings. Bu ...

While translating in Angular's dark mode, I noticed that the background property disappears from the card-content

`I implemented a toggle-switch in my Angular project using <mat-slide-toggle></mat-slide-toggle> to switch between dark mode and light mode. However, when I switch to dark mode and translate my application, the background property of the card-c ...

Utilizing the get and set methods to alter the structure of a string, but encountering the issue where the set method is

Upon receiving a datetime through an HTTP request, I need to format it before utilizing it. To achieve this, I utilize the get and set methods in my code. However, I noticed that the set method is never invoked. This is how my component (AdminComponent) l ...

What is the best way to iterate through all class properties that are specified using class-validator?

I have a class defined using the class-validator package. class Shape { @IsString() value?: string @IsString() id?: string } I am trying to find a way to retrieve the properties and types specified in this class. Is there a method to do s ...

Issue with updating view in React Native/Javascript after an asynchronous fetch operation. Execution order may be invalid

Below is the code I've written to fetch data using fetch() and display an output only after fetching it. However, the view fails to update after the asynchronous call. Since I'm new to react native async calls, I would appreciate some help on thi ...

What are the steps to incorporating the pick function in TypeScript?

The TypeScript documentation mentions a pick function that is declared but not implemented. In an attempt to create a simplified version, I wrote the following: function pick<T, K extends keyof T>(obj: T, key: K): Pick<T, K> { return { [key]: ...

Passing RxJs pipes as a parameter

Is there a way to pass pipes as parameters? For example: var mypipes = [ pipeA(() => { alert("a"); }), pipeB(() => { alert("b"); }) ...

Retrieving the property of a union type comprising a void type and an unnamed type

Currently, I am working on a project involving GraphQL. In my code, I have encountered a GraphQLError object with a property named extensions. The type of this property is either void or { [key: string]: any; }. Whenever I try to access any property within ...

How can I efficiently iterate through the array of index IDs and then iterate individually through the communes, categories, and locations?

Currently, I am developing a nodejs typescript API where I am retrieving an array of objects using a map loop. The data for "communes", "category", and "location" is fetched from another API function based on the issuerId. However, I am facing issues with ...

A handy tool for easily previewing JavaScript code based on my TypeScript within Visual Studio

Recently I decided to dive into TypeScript. I am eager to find extensions for VisualStudio or Re# that can display live JavaScript based on the TypeScript code I write. Any suggestions for tools like this? Currently, I am using VS 2015 with Re#. ...