Create a new TypeScript type that contains multiple properties with the same data type

I'm looking to create a Theme that includes multiple color options, all of which are strings.

Is there a way to simplify this? Can I just say that all properties of ThemeColors are strings? thanks

type ThemeColors = {
  white: string;
  black: string;
  grey: string;
  ligthGrey: string;
  headerBackground: string;
  headerWhite: string;
  redError: string;
  greenSuccess: string;
  yellow: string;
  orange: string;
  peach: string;
  pink: string;
  purpleLight: string;
  purple: string;
  violet: string;
  blue: string;
};

thanks

Answer №1

If you are concerned about the specific keys, you can designate them as a union of string literal types:

type ThemeKeys = "white" | "black" | "grey" | "ligthGrey" |
  "headerBackground" | "headerWhite" | "redError" |
  "greenSuccess" | "yellow" | "orange" | "peach" | "pink"
  | "purpleLight" | "purple" | "violet" | "blue";

Then, create ThemeColors as a mapped type over those keys with the property type of string:

type ThemeColors = { [P in ThemeKeys]: string };

This will display as:

/* type ThemeColors = {
    white: string;
    black: string;
    grey: string;
    ligthGrey: string;
    headerBackground: string;
    headerWhite: string;
    redError: string;
    greenSuccess: string;
    yellow: string;
    orange: string;
    peach: string;
    pink: string;
    purpleLight: string;
    purple: string;
    violet: string;
    blue: string;
} */

You can also achieve this using Record<ThemeKeys, string> with the Record utility type.


If you are not concerned about the keys and simply want to define that the properties are always strings, you can use an index signature like:

type ThemeColors = { [k: string]: string };

This is equivalent to Record<string, string>, as explained in other answers to this question.

Playground link to code

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

Can a custom type be created in Typescript that permits objects but excludes Errors?

Currently working on resolving an odd scenario with a logger. Essentially, calls like log({ info: 'information' }) function as expected, but log(new Error()) falls short. While no solution is readily available, the goal is to override the log m ...

Using RxJs in an Angular 2 application to enable row selection in a table by detecting mouse movements

Check out this example of an Angular 2 application with row selection in a table: https://plnkr.co/edit/HdQnWqbg9HloWb4eYGHz. The row selection functionality is implemented using mouse event handlers (mousedown, mousemove, mouseup). Below is the template ...

Incorporating rows into the angular table form dynamically using a loop

I am looking to enhance the Angular form by incorporating a for loop for each element in the tax_rate_details array. This way, the form text boxes can be automatically filled with the corresponding data values. I wish to add a new row for every entry in th ...

Apollo-Server presents errors in a polished manner

It seems like the question explains itself adequately. I am currently using 'apollo-server-core' version 3.6.5 Desired Errors: { "errors": [ { "message": "Syntax Error: Unexpected < ...

In a NextJS and Vite app, what is the recommended value for setting `jsx`?

To prevent encountering the following error ReferenceError: React is not defined ❯ Module.Home [as default] src/app/page.tsx:2:3 1| export default function Home() { 2| return <div>Home of Coach-Next</div>; | ^ 3| ...

Utilizing ExpressJS in a NodeJS application with ES6 and Typescript

After confirming my information, I discovered that in an ES6 application, it is necessary to import dependencies using import .. from '..' instead of var .. = require('..'). I made the necessary changes to the imports, but encountered ...

Define an object by extracting properties from an array of objects

Is there a way to refactor this code to remove the need for explicit casting? type A={a:number}; type B={b:string}; let a:A={a:0}; let b:B={b:''}; function arrayToObject<T>(array:T[]):T { return array.reduce((r,c) =>Object.assign ...

Sometimes, it feels like TypeScript's async await does not actually wait for the task to complete before moving on

Recently, I have been transitioning to using the async await pattern more frequently instead of the traditional Promise syntax because it can help in keeping the code structure cleaner. After some experimentation, I felt like I had a good grasp on how to u ...

Exploring the Differences Between Native Script and Ionic: A Guide to Choosing the Right Framework for Your Hybrid Apps

When deciding between Ionic and Native Script for hybrid app development, which technology would you recommend? Or do you have another suggestion knowing that I am familiar with Angular 6? Also, I am looking for a Native Script tutorial, preferably in vide ...

Working with objects in *ngFor in Ionic 2

I am utilizing Ionic 2 and attempting to display the content of a key-value array using an object. In order to display my collection, I am using a pipe in my HTML. Below is my HTML code: <ion-list> <ion-item *ngFor="let event of this.pdata. ...

Utilizing Vue and Typescript for efficient dependency injection

After attempting to use vue-injector, I encountered an issue as it was not compatible with my version of Vue (2.6.10) and Typescript (3.4.5). Exploring other alternatives, there seem to be limited options available. Within the realm of pure typescript, t ...

Strange occurrences with Typescript compiler when interface doesn't align

There's something strange happening with the Typescript compiler when I use an interface in certain cases. For instance, everything works perfectly fine here with no errors: interface Bar { letter: 'a' | 'b'; } declare class F ...

The 'performance' property is absent in the 'FirebaseApp' type, which is necessary in the 'App' type

Encountering an issue during a fresh installation of Angular 7.2 and Firebase, specifically getting this error: ERROR in node_modules/@angular/fire/firebase.app.module.d.ts(17,22): error TS2420: Class 'FirebaseApp' incorrectly implements interfa ...

I am eager to incorporate the Twilio API into my project, however, I am encountering an error when trying to import Twilio into my TypeScript file

I am currently integrating the Twilio API into my project, but I'm encountering difficulties importing it into my TypeScript file. Interestingly, when I use the API in a JavaScript file, everything works smoothly without any issues. Below are the err ...

Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class. For instance: Consider the following string array: let stringArr = ['player1score', 'player2score', 'player3score' ...

How can I utilize the Redux store outside of a component in a React application with ASP.NET Core and TypeScript?

While I have some experience with React, I am new to using Redux. Luckily, Visual Studio 2017 comes with a built-in template for React + Redux under .NET Core 2.0. About my environment: Visual Studio 2017 React 15.6.1 TypeScript 2.4.1 Redux 3.7.1 Rea ...

Visibility of an Angular 2 directive

It's frustrating that I can't change the visibility of a reusable directive in Angular2. 1) Let's say I have a login page. I want to control the visibility of my navbar based on whether I am on the login page or logged in. It should be hid ...

what is the best way to eliminate comments from nested arrays when using useReducer?

Can someone help me figure out how to use useReducer and useContext to manipulate global state? I specifically need to know how to delete comments using useReducer. Data Structures View the interface image here Sample Data Array export const listsData:IDa ...

Implementing Dynamic FormControl Values within FormGroup in Angular: A Step-by-Step Guide

GenerateFields(customControl, customValue): FormGroup { return this.fb.group({ customControl: new FormControl(customValue), }) } I am looking for a way to dynamically add the value of customControl from the parameter passed in the Ge ...

Error SCRIPT5009: 'query' is undefined

One of my goals is to trigger a function when the user moves the mouse out of an input field. <input #filter onmouseout="search(filter.value)"> The defined function looks like this: search(term: string): void { for(var i = 0; i < this.emp ...