Exploring the Strategy of Incorporating Dynamic Keys into TypeScript for Easy Referencing

I am facing a scenario where I receive keys from the backend and need to design an interface based on these keys. By creating a dynamic interface, I can easily bind these properties.

const KEYS_FROM_API = ['ARE_YOU_SURE', 'NOT_NOW', 'GO_BACK'];

// defining type dynamically
type DYNAMIC_KEYS_TYPE = typeof KEYS_FROM_API[number];

// creating dynamic interface using Record
type ResultType = Record<DYNAMIC_KEYS_TYPE, string>

// RESULT stores key value pairs with the type of dynamic interface, ResultType
const RESULT: ResultType = { ARE_YOU_SURE: 'Are You sure', NOT_NOW: 'Not Now', GO_BACK: 'go back'}

// works as expected
console.log(RESULT.ARE_YOU_SURE, RESULT.NOT_NOW, RESULT.GO_BACK);

The provided code meets the expectations and there are no linting errors, as the RESULT constant has a type that includes all the properties from the interface.

Now, I am interested in creating the DYNAMIC_KEYS_TYPE dynamically using the KEYS_FROM_API array. Instead of hardcoding it like in the above example, I am looking for a way to generate this type based on the contents of the KEYS_FROM_API array.

I need assistance in creating the DYNAMIC_KEYS_TYPE from the KEYS_FROM_API array.

Answer №1

To make the data type of KEYS_FROM_API more strict than just string[], you should include 'as const' when defining it. This way, you can then reference the type as typeof KEYS_FROM_API[number];

const KEYS_FROM_API = ['ARE_YOU_SURE', 'NOT_NOW', 'GO_BACK'] as const;

// expected: type DYNAMIC_KEYS_TYPE = 'ARE_YOU_SURE' | 'NOT_NOW' | 'GO_BACK'
type DYNAMIC_KEYS_TYPE = typeof KEYS_FROM_API[number];
//   ^? type DYNAMIC_KEYS_TYPE = 'ARE_YOU_SURE' | 'NOT_NOW' | 'GO_BACK'

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

What is the best way to transform a list of Python+Flask objects into a list of JavaScript objects?

Here's a Flask application that showcases a list of objects. from flask import * app = Flask(__name__) class Entry: def __init__(self, name, surname): self.name = name self.surname = surname entries = [] entries.append(Entr ...

Upon transitioning from typescript to javascript

I attempted to clarify my confusion about TypeScript, but I'm still struggling to explain it well. From my understanding, TypeScript is a strict syntactical superset of JavaScript that enhances our code by allowing us to use different types to define ...

Database query not appearing on node.js route

As a newcomer to javascript and nodejs, I have encountered an issue that I'm hoping to get some clarification on. I am currently working on a simple API and facing difficulties in understanding why a certain behavior is occurring in my code. app.get( ...

Obtain JSX content from a React Component that has been imported

As part of our library documentation efforts, I am looking to convert a React Component function into JSX format. To illustrate, let's consider a rendered Button component and showcase the code used to create it. One approach could be to simply read ...

Implementing tailwindcss styles in a typescript interface with reactjs

In my code, I have a file named types.ts that defines an interface called CustomCardProps. I pass this interface to the CustomCard component within the home.tsx file. Additionally, I have a folder named constant with an index.ts file where I store values o ...

Building a Div Tag Layout with CSS for Full Width and Left Position of 300px

Experiencing some trouble with styling a div element. My goal is to have the div start at left:300px and stretch across the entire width of the browser window. However, when I apply width:100%, the div extends beyond the boundaries of the browser screen. ...

What does Typescript compile when aiming for ES5 / ES3?

I'm currently grappling with the nuances of when the Typescript compiler decides to transpile code in order to align it with my designated target ECMAScript version (ES5 or ES3). As an example, TSC has no problem transpiling for(var int of intArray); ...

Utilizing external clicks with Lit-Elements in your project

Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progres ...

Tips for navigating through an array incrementally in a Controller using input provided by the user in the View

Greetings, I am currently working on a small website project using WAMPserver. The site is structured following an MVC design pattern. In one part of the process, I generate an array of strings in the controller. My goal is to display each element of this ...

The passport is experiencing an authentication issue: The subclass must override the Strategy#authenticate method

After attempting to authenticate and log in a user, I encountered an error message stating: Strategy#authenticate must be overridden by subclass. How can I resolve this issue? What could be causing this error to occur? Concerning Passport.js const LocalS ...

Is there a memory leak causing Node.js memory growth in the (system)?

I have come across a peculiar memory leak in our live environment, where the heap continues to grow due to (system) objects. Heap snapshot Here is a memory dump showing a spike in memory usage up to 800MB: https://i.sstatic.net/vvEpA.png It seems that t ...

Tracking changes to payment methods when an order is modified through the WooCommerce backend

In the midst of working on a project involving WooCommerce, I am currently focused on integrating a new feature. This feature involves adding an order note whenever a user modifies the payment method during the order editing process within the WooCommerce ...

Tips for creating a seamless horizontal scrolling effect in Angular when hovering (automatically)

One of the components I'm working on features a gallery with an X axis orientation. <div class="gallery"> <div (mouseenter)="scrollTo('left', $event)" (mouseleave)="clearIntervalRepeater()" class="left"></div> < ...

stop the leakage of CSS and JS from the subtree to the document through the inverse shadow DOM mechanism

My page contains dynamic HTML content that I want to incorporate. The dynamic content consists of only HTML and CSS, without any JavaScript. However, I have some custom global CSS styles and JS logic that need to be implemented along with this dynamic con ...

Intellij2016 is issuing warnings for the sass use of the :host selector in Angular2 code

One interesting feature of Angular 2 is the special selector it uses to reference its own component: :host display: block height: 100% !important width: 100% text-align: center position: relative However, Intellij does not provide a way to supp ...

Exploring the wonders of Onsen UI's ng-repeat feature combined

Facing a major issue with my app, and I suspect it's due to the asynchronous call. The HTML section looks like this: <ons-list ng-repeat="item in newsEventi.items"> <ons-list-header class="news_titolo_lista">{{item.categoria}}</ons ...

Creating a highly innovative server infrastructure tailored for Dojo applications with exceptional features

Recently, I have been using web2py for my projects and have found it incredibly useful in creating RESTful web applications. However, I am now looking to expand my skills in JavaScript by developing a more modern and dynamic client-side application that re ...

Implementing a transition to activate upon data loading in a Vue.js component – here's how!

Currently, I am immersed in a project utilizing vue.js and vue-router. Within my Vue application, I have a section dedicated to displaying news fetched from an API that functions as a blog. To load this news data into the component, I am utilizing the rou ...

What is the best way to create a TypeScript type for React props that only allows prop B to be used if prop A is included in the component?

My component Text has 2 props: isHideable: boolean and hidden: boolean. How can I only allow Hidden as a prop when isHideable is set to true? Currently, both isHideable and hidden are being accepted which is not the desired behavior: type Props = { chi ...

Diving deeper: Angular and NPM dependencies compared to devDependencies

After doing a lot of reading on this topic and following this very informative post at: What is the distinction between dependencies, devDependencies, and peerDependencies in an npm package.json file? I have learned that dependencies should include all ru ...