TS type defined by JS constants

I am currently working on a project that involves both JavaScript and TypeScript. I am trying to find a solution to reduce code duplication when using JavaScript string constants by converting them into TypeScript types.

For example, let's say I have constants for different log types:

// logTypes.js    
export const ERROR = 'error'
export const INFO = 'info'

To reuse these constants, I decided to reexport them:

// constants.js    
export * as LOG_TYPES from './logTypes.js'

Now, my goal is to define a TypeScript type for these constants:

// types.d.ts
import { LOG_TYPES } from './constants'

export type LogType = ???

I could simply declare the type this way:

// type LogType = "error" | "info", excellent
export type LogType = typeof LOG_TYPES.INFO | typeof LOG_TYPES.ERROR 

However, I believe this approach is redundant and can be hard to maintain if new constants are added in the future.

What I actually want is something like this:

// Does not work as desired
// type LogType = any, meh
export type LogType = typeof LOG_TYPES[string]

I understand the distinction between types and values, but I think this specific part of import/export should be statically analyzable, so there must be a solution that I am unaware of.

Answer №1

Indeed, the concept is to use keyof typeof LOG_TYPES because you cannot index typeof LOG_TYPES with a string:

type LogType = typeof LOG_TYPES[keyof typeof LOG_TYPES]
//   ^? "error" | "info"

Link to 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

Utilizing React-hook-Form to transfer data between two SelectBoxes

This simple logic is causing me some trouble. Despite using react-hook-form, I thought this would be easy. However, after struggling with it for over a week, I'm still facing challenges. I'm incorporating nextUI components into my project. < ...

Error message saying 'Callback has already been invoked' returned by an async waterfall function

I'm facing an error that I understand the reason for, but I'm unsure how to resolve it. Here's a breakdown of my initial function: Essentially, I am making a get request for all URLs stored in the database and then, for each URL response, I ...

Having trouble getting routing to function properly with react-router-dom

I'm currently assisting a friend with completing a React Project. I'm facing an issue while trying to set up routing using react-router-dom. The components inside the <switch> tag are not functioning properly. Below are snippets of my code: ...

When trying to append in jQuery, the error "JQuery V[g].exec is not a

Attempting to create a script that adds a table to a div within the website using the following function: function generateTable(container, data) { var table = $("<table/>"); $.each(data, function (rowIndex, r) { var row = $("<tr/>"); ...

What is the proper method for setting initial values for scope upon loading the view using AngularJS and ngInit?

For the last few weeks, I've been immersing myself in AngularJS, studying large-scale applications to gain insights into real-world development practices. One common pattern I observed is the use of ng-init="init()" when loading a view - essentially c ...

What is the best way to deliver HTML content to an ASP.NET MVC JSON function?

Here is my jQuery code that I have written along with the json function called InsertMatlabJson. However, I am facing an issue where no text is being passed to the .NET json function. function insert() { var url = '<%=Url.Content( ...

What are the possible arguments for the event type onInput?

While diving into the world of html / javascript / vue, I stumbled upon the following code snippet. <input type="text" onInput="doAction(event);"> <script> var mesdata = { message: 'type your m ...

Execute JavaScript function after the window has finished loading, regardless of any asynchronous downloads

In my app, there is an initialise function that I want to execute only when two conditions are met: first, the window has finished loading ($(window).load()), and second, Typekit has loaded. $(window).load(function() { try { Typekit.load({ act ...

Load a page from a different domain using uframe

Looking for a solution to successfully load an external URI using uFrame. Currently encountering an "Access Denied" issue when attempting to do so on Firefox. Any suggestions? ...

What could be causing the cyclic dependency problem after upgrading to Angular 9?

I am experiencing an issue with a specific file containing the following code: import { Injectable } from '@angular/core'; import { I18n } from '@ngx-translate/i18n-polyfill'; import { isNumber } from 'lodash'; import { Confir ...

Steps to fix issues with Cross-Origin Read Blocking (CORB) preventing cross-origin responses and Cross Origin errors

var bodyFormData = new FormData(); bodyFormData.set("data", "C://Users//harshit.tDownloads\\weather.csv"); bodyFormData.set("type", "text-intent"); //axios.post("https://api.einstein.ai/v2/language/datasets/upload", axio ...

Ways to pause JavaScript execution until a function completes its task

Is it possible to pause JavaScript execution until a specific function finishes in JavaScript/NodeJS? For instance: https://i.stack.imgur.com/Ta8pj.png Imagine the first line of code triggers an alert, and JavaScript stops executing until the user interac ...

What is the best way to incorporate a minimum width and maximum width in CSS that add up to 100% when necessary?

Can anyone help me find CSS rules that can set a fixed width for an element (width: 500px) but also allow it to be responsive with max-width: 100% if the container is narrower than the element? I saw this example and it works perfectly: .elem { width: 60 ...

effective ways to extract objects from nested structures using a specific identifier

In this sample data, I am looking to filter an object based on its ID key let myData = { "nodeInfo": { "9": { "1": { "ID": "14835" ...

Aligning a div with absolute positioning vertically

There are two elements positioned side by side: an input field and a div. The div is absolutely positioned inside a relative element and placed to the right of the input. The input field has a fixed height, while the height of the div depends on its conte ...

How to add an OnClick listener to a cell element in a table built with the Tan

I am currently working on a project using React and trying to implement a table. I want to show an alert when a header cell in the table is clicked, displaying some information. However, I have been struggling to find assistance on adding a click listener ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

Resolving the issue of "Cannot set properties of null (setting 'innerHTML') at HTMLInputElement.loader" involves identifying the root cause and implementing

Need assistance with this code. Although I believe everything is correct, it still isn't working as expected. The error mentioned in the title comes up whenever I try to use it. I've made multiple modifications to the code but it's still not ...

Enhancing Material-UI component [TreeView] with drag and drop functionality using react-dnd

I have encountered an issue with my TreeView implementation. Whenever I try to drag and drop a TreeItem, all of its child TreeItems move along with it. Is there a way to enable drag'n'drop functionality for just one TreeItem without affecting its ...

Error 404 in NodeJS: Page Not Found

I recently started working with NodeJS to develop an ecommerce application. I have a ready-made design and all the front-end components built using AngularJS code. Everything seems to work fine - when clicking on any menu, the page content changes along wi ...