Generating dynamic type keys in Typescript

I am looking to dynamically generate keys by combining the keys of other types, similar to creating object keys dynamically.

type Swatch = {
  dark: string;
  light: string;
};

type ColorTheme = {
  primary: Swatch;
  secondary: Swatch;
};

// The desired outcome is
type CombineType: {
  // These keys are generated dynamically as a combination of Swatch and ColorTheme keys

  // primaryDark: string
  // secondaryDark: string
}

Answer №1

To accomplish this task, you can create a "generator" generic type that will provide the desired result.

type First = {
  attribute1: string;
  attribute2: string;
};

type Second = {
  property1: string;
  property2: string;
}

type MergeKeys<FK, SK> = 
  FK extends string ?
    SK extends string ?
      `${FK}${Capitalize<SK>}`
    : never
  : never;

type CombineObjects<F,S> = {
  [key in MergeKeys<keyof F,keyof S>]: string;
};

type Result = CombineObjects<First, Second>;

The MergeKeys type simply combines the provided key values. The CombineObjects type is a straightforward generic type that receives two parameters and produces a type where the keys are merged using keyof on both input parameters.

It would be advisable to enhance these types further to ensure only objects can be passed as arguments and to achieve complete type coverage :)

For a functional example, please refer to the code snippet in the Typescript Playground

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

Validating checkboxes for multiple selections

I have checkboxes in each row: <form id="CustomerNEmployeeForm"> <table> <tr id="row1"> <td> <div class="i-checks"><input id="checkboxCustom1" type="checkbox" nam ...

The Javascript regex allows for the presence of positive and negative numbers, with the option of a single minus symbol

oninput="this.value = this.value.replace(/[^-0-9.]/g, '') This code snippet is utilized in my current project. However, there seems to be an issue where the input can contain more than one minus sign, as shown here: ---23 To address this p ...

Changing the value of a JavaScript variable within the .Net Codebehind

I've run into an issue where I need to update a JavaScript variable after post-back. My initial approach was to use the ClientScript.RegisterStartupScript function, which worked fine during the first page load but failed on subsequent postbacks. I inc ...

Tips for LoadingUrl in WebView from a Different Class on Android App

I am a beginner in Android app development and Java. I want my app to use a WebView to display its content. The user should be able to interact with HTML elements, such as buttons or links, which will then send requests to my Android Java class to navigate ...

Issue with my JavaScript code for customizing checkboxes: the else condition is not being triggered

I'm currently in the process of customizing my own version of "checkboxes" by styling label elements and moving the actual checkbox off-screen. This is the approach I decided to take based on the design and functionality requirements presented to me. ...

Exploring the power of jQuery's deferred method and utilizing the ajax beforeSend

Using the deferred object in $.ajax allows for: Replacing the success-callback with the deferred-method done() Replacing the error-callback with the deferred-method fail() And replacing the complete-callback with always() When using: var jqxhr = $.ajax ...

Begin counting starting from 1 all the way up to 24, then feel free

I've developed a counter that increments from 0 to 24, and once it reaches 24: setInterval(function(){DayAndNight()}, 1000); var iState = 12; function DayAndNight() { //console.log('test'); switch(iState) ...

What is the process for setting the active state for HtmlBodyElement?

I attempted to use the following method: document.querySelector('body').setActive(); However, I encountered an error: TS2339: Property 'setActive' does not exist on type 'HTMLBodyElement'. Any suggestions on how to resolve t ...

Error encountered while attempting to perform date subtraction (Interpolation not supported)

Hey there, I created a basic function to subtract dates in JavaScript, but I keep getting an error. Here is the JS code: $scope.tosum = function(d1, d2) { var d3 = new Date(d1.getTime() - d2.getTime()); console.log(d3); return d3; }; This is the error ...

How can I determine the type of a component in Vue.js?

I'm currently developing a vuejs application using typescript and my goal is to leverage the available typings as much as possible. For the most part, the typings and type inference work smoothly without any issues. However, in certain parts of my c ...

I'm looking for a more efficient and meaningful method to showcase the items from my database in my store that will allow me to easily categorize and organize them in the future

As a beginner, I know it's not recommended to echo HTML code, but I haven't found a better way yet. Currently, I allow the user to change the SQL query to sort items, even though this leaves me vulnerable to SQL injections. I'm open to new s ...

Displaying an array of JSON objects in ReactJS by parsing them

Recently, I've encountered an odd issue with my React App. I am attempting to parse a JSON object that includes arrays of data. The structure of the data looks something like this: {"Place":"San Francisco","Country":"USA", "Author":{"Name":"xyz", "Ti ...

Error encountered when attempting to assign a value of the original data type within the Array.reduce function

I am in the process of developing a function that takes a boolean indicator object like this: const fruits = { apple: false, banana: false, orange: false, mango: false, }; Along with an array such as ['apple', 'orange']. The go ...

What is the proper way to activate the oninput event once a string has been inserted into a text box

I am trying to insert a string into a textbox using the JavaScript code below: document.querySelector('textarea').value = '0a06282c0241057a10011805220d080510bea3f493062a03010c1628f1a6f493063002382b4001481482010f383634333233303532343736343839 ...

I am in search of a JavaScript or jQuery plugin for an HTML slider with a unique range functionality

I've been searching online but couldn't find a slider like the one shown in the attachment. Can anyone help? Is there a way to create this specific slider or is there an existing plugin or library for it? Please refer to the image below :https:/ ...

I am looking to dynamically print countries from an array in my code based on the selected option

I'm in need of some simple code assistance. I want to display a list of countries that correspond to a selected letter, but I'm struggling to do so dynamically at the moment. For example, if I select the letter A from a dropdown menu, I want the ...

Remove element in array[x] removes the value without deleting the entire element

I encountered an issue with an object that contains duplicate values. To address this, I tried using delete new_object[1] to remove the value. However, upon checking the console, the object 0800 displayed "undefined". ["293", undefined, "298", "297"] ...

Removing a specific value from a Pinia reactive data store

Currently, I am developing a multi-step registration form that includes an option for users to upload an avatar. As it's a complex form, I've decided to store the data in a Pinia store until the final submission. Everything seems to be functionin ...

Alignment issue with Ul dropdown menus and shadow

After stumbling upon a fascinating menu design at this link, I decided to tweak it for center alignment by following the advice on this forum thread. Unfortunately, my efforts have hit a roadblock - the drop down menus aren't aligning as intended and ...

How can AngularJS achieve ng-repeat functionality with multiple variables similar to ng-init?

When using ng-init, you have the ability to utilize multiple variables: ng-init="var1=value1; var2=value2" I attempted something similar with ng-repeat but unfortunately it did not work as expected ng-repeat= "var1 in var1s; var2 in var2s" Is there a p ...