What is the best way to specify the type of a dictionary with keys that are a subset of a union of literal types?

When working with TypeScript, I have a union literal type named Color defined as:

export type Color =
  | 'red'
  | 'green'
  | 'blue'
  | 'teal'
  | 'purple'

My challenge is to define the type of a dictionary where some of the keys are from the values of Color, and the values are strings.

For example:

const COLOR_MAP = {
  red: 'Cool',
  green: 'Not so cool'
}

I need to create a type for COLOR_MAP so that I can access its values using a string that matches the type Color.

Answer №1

To create a comprehensive map, utilize either Record<Color, string> or { [key in Color]: string }.

For a non-comprehensive map, consider using

Partial<Record<Color, string>>
or { [key in Color]?: string }.

If you need a specific subset of the union that is predetermined at compile-time, use Extract:

Record<Extract<Color, 'red' | 'teal'>, string>

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 reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

Create a custom button in Material-UI using Styled-components, and integrate it with React

I'm currently working on a project using React, TypeScript, and styled components along with the material-ui library. I have created styled material-ui buttons as shown below: import React from 'react' import styled from 'styled-compone ...

Error message TS2339: The method 'findAll' is not defined in the current context

Despite following the Sequelize guide for TypeScript configuration, I am unable to resolve an issue with my database connection. The connection is active, but I am struggling with a specific type problem: TSError: ⨯ Unable to compile TypeScript: controll ...

Navigating any object array in TypeScript and retrieving its properties

Consider the following JSON data object: var dataObjects = [ { "Name": "Date & Time", "Type": "Date", "Value": "2019-12-11" }, { "Name": "Activity", "Type": "String", ...

What is the best way to set a value for an undeclared control in a reactive form?

I have not declared an email control in the HTML file, but I have declared it in my form group. I want to set the email value that is receiving in the customers to the email control. <form class="form-row" [formGroup]="form"> ...

Creating a customizable filter by using the function of an object

I am currently developing a customizable dynamic filter system, similar to the functionalities offered by Yahoo Screener. To achieve this, I have defined an interface for the available filter fields: export interface FilterField { label: string; se ...

Autocomplete feature in Angular not showing search results

I am currently using ng-prime's <p-autocomplete> to display values by searching in the back-end. Below is the HTML code I have implemented: <p-autoComplete [(ngModel)]="agent" [suggestions]="filteredAgents" name="agents" (completeMethod)="f ...

An error is encountered with the 'this' keyword in the map operator of Angular

I am in the process of developing a custom validator for a Slug form control and have encountered an issue with my code. ngOnInit() { this.slugCtrl.setAsyncValidators(this.slugValidator); } slugValidator(control: AbstractControl) { const obs1 = c ...

Error in Writing Functional Components with Typescript in React

I am struggling to create a versatile functional component and encountering issues like the one shown in this https://i.stack.imgur.com/WQkKg.png: Here is the code snippet: interface IAppTable<Type> { height: number; data: Type[]; tableLayout: ...

Looking for ways to enhance the readability of JSON in your React-Typescript application?

After completing Stephen Grider's React and Typescript course on Udemy, I developed the JBook app. One of the challenges I encountered was ensuring that the content from a user's local file is displayed clearly in JBook. Currently, all content is ...

The data remains undefined even after being initialized in the constructor

My goal is to extract queryParams from a URL and leverage that information to resolve data in the following manner: data = { searchValue: null || undefined }; constructor(private http: HttpClient, private route: ActivatedRoute) { route.queryParams.su ...

How can a child component trigger an event in its parent component?

Currently, I have tabs implemented with a form and a button in tab1. In the parent component, there is an event that deactivates the current tab and activates the next one. Can anyone advise on how to call this event from the child component? gotosecond ...

The error message "Property <property> is not recognized on the type 'jQueryStatic<HTMLElement>'" is indicating an issue with accessing a specific property within the TypeScript codebase that utilizes Angular CLI, NPM,

My Development Environment I am utilizing Angular, Angular CLI, NPM, and Typescript in my web application development. Within one of my components, I require the use of jQuery to initialize a jQuery plugin. In this particular case, the plugin in question ...

Picking up Angular component property values within a callback function from Google Charts

Trying to utilize the angular-google-charts library in Angular 13.2, I am working on creating a TreeMap with a customized tooltip feature. The GoogleChartComponent offers an options property called generateTooltip which requires a callback function. My goa ...

Invoke a function within the <img> tag to specify the source path

I have been attempting to achieve something similar to the following: <img id="icon" class="cercle icon" src="getIcon({{item.status}})" alt=""> This is my function: getIcon(status){ switch (status) { case 'Ongoing': ret ...

Unable to access default route

My application is structured as follows: app.module.ts const routes: Routes = [ { path: '', loadChildren: './modules/main/main.module#MainModule' }, ]; @NgModule({ declarations: [ AppComponent, ] ...

How can I save a TypeScript object to Firebase using serialization?

Having an issue: Within my angular application, I have implemented a lot of classes with inheritance. However, upon attempting to save these objects to Firebase, I encountered an error indicating that I am trying to persist custom objects which is not supp ...

In TypeScript, if all the keys in an interface are optional, then not reporting an error when an unexpected field is provided

Why doesn't TypeScript report an error when an unexpected field is provided in an interface where all keys are optional? Here is the code snippet: // This is an interface which all the key is optional interface AxiosRequestConfig { url?: string; m ...

"Enhance Your Search with PrimeNG's AutoComplete

Currently, I am attempting to implement the autocomplete feature from primeNg based on their documentation, but I am facing issues with displaying the suggestions. Firstly, I added the AutoComplete module by importing it: import { AutoCompleteModule } fro ...

Ways to retrieve a particular element within an array

I am looking to access each individual element of the "to" value within the children property of my array. const items = [{ name: 'Administrator', children: [ { name: 'Catalog', to: 'catalog' }, and he ...