Import all constants that have been exported in ES6 TypeScript and store them as an array

I am faced with the challenge of exporting multiple constants that I will later need to import and iterate through as an array. Due to my use of generics (OptionInterface) and the necessity to maintain type validations, I cannot simply place all constants in one object for export.

Currently, I am exporting each constant as a named export and then exporting them all as an array. However, there is a concern that another developer may overlook the requirement to add a new element to the exported array.

For instance:

//ElemSettings.tsx
export interface ElemProps<OptionInterface = any> {
  title: string,
  key: string,
  options: OptionsInterface[] 

export interface SpecialOption {
 s1: string,
 s2: number
}


//Elements.tsx - desired exports
export const elemOne: ElemProps {
  title: 'element One',
  key: elemOne'
  options: [1,2,3]
}

export const elemTwo: ElemProps {
  title: 'element Two',
  key: elemTwo'
  options: [1,2,3]
}

export const elemThree: ElemProps<SpecialOption> {
  title: 'element Two',
  key: elemTwo'
  options: [{s1:'one',s2:1},{s1:'two',s2:2}]
}

//Current export method
export const elems: Array<ElemProps> =
  [elemOne, elemTwo, elemThree]



//user.tsx
import { elems } from 'Elements';

const doSomething = () => { 
      elems.map(...)
}

If I attempt to simplify the export process by importing all elements, like this:

import * as elems from 'Elements';

and then use it as shown in doSomething function, an error occurs:

Property 'map' does not exist on type 'typeof import("Elements")'.

Do you have any suggestions on how to export all constants as an array while preserving the typing?

Answer №1

When you use the syntax <code>import * as elems
, it will generate an object structure like the one shown below:

{
    "elemOne": ...
    "elemTwo": ...
    ...
}

To access the values exported by this object, you can utilize Object.values to convert them into an array:

import * as elems from 'Elements';

const doSomething = () => { 
  Object.values(elems).map(...)
}

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

Revamping the spec.ts.cjs snapshot with the latest Node-tap Protocol updates

After using the example found on node-tap-snapshot-examples, I successfully created a snapshot by running the command tap tagger.test.mjs --snapshot for the modified TS version of the following test. // tagger.spec.ts import t from 'tap' import t ...

Typescript automatically determines the return types of functions created by the openapi-generator as Promises holding any type of data

After running the Swagger Petstore example API through OpenAPI Generator using the command docker run --rm -it --name openapi-gen -v "$(pwd)":/mnt/workdir -w /mnt/workdir openapitools/openapi-generator-cli generate -i petstore.yaml -g typescript- ...

Update the name of the table header dynamically based on the checkbox that is selected in Vue

I am working on a project where I have checkboxes that determine the header of my table based on selection. Starting from <th>Default</th>... If checkbox1 is checked, the header will change to "CheckBox1". If checkbox2 is checked, the header ...

Import a JSON file into Angular 8 and parse its contents

My code is intended to read and upload a JSON file (ARM template), but I am encountering an issue where this.updateObj appears as undefined in the console.log. Below is my code: onChange(fileList: FileList): void { var file = fileList[0]; var fileR ...

Mapping nested JSON to model in Angular2 - handling multiple API requests

Having trouble integrating two HTTP API Responses into my Model in Angular 2. The first API Call returns data like so: [{ "id": 410, "name": "Test customdata test", "layer": [79,94] }, { "id": 411, "name": "Test customdata test2", ...

What is the best way to customize fonts for PDFMake in Angular projects?

Recently, I delved into the PDFMake documentation in hopes of creating a document for my Angular application. Along the way, I stumbled upon queries like this one, but unfortunately, found no answers. I am curious if anyone can offer insight or provide a ...

Npm was stuck at the url-resolver, failing to compile both the development and production versions

62% building 702/705 modules 2 active ...w/yyyyyy/node_modules/path-loader/index.js??ref--7-6!/var/www/yyyyyy/node_modules/sass-compiler/dist/cjs.js??ref--7-10!/var/www/yyyyyy/resources/sass/theme.scss Any tips on troubleshooting why the process is gettin ...

The MUI next Tooltip fails to display upon hovering

While using Material-UIv1.0.0-beta.34 Tooltip with Checkbox and FormControlLabel, I noticed that the tooltip works as expected when hovering over the label in one case. However, when I tried creating a new component(custom) with FormControlLabel and Checkb ...

Angular searchbar issue: Unable to assign parameter of type 'unknown' to parameter of type 'string'

I've been working on an Angular app to fetch data from an API successfully. However, I'm currently facing a challenge while implementing a search function in my component.ts file. Here is the entire service code: import { Injectable } from &apos ...

NGXS Alert: Unable to resolve parameters for TranslationEditorState: (?)

I'm currently implementing NGXS for state management within my Angular 9 application. I've encountered a specific issue where any attempt at dependency injection in one of the state classes results in an error message stating "Error: Can't r ...

Converting an array of objects into a unified object and restructuring data types in TypeScript

A few days back, I posted a question regarding the transformation of an array of objects into a single object while preserving their types. Unfortunately, the simplified scenario I provided did not resolve my issue. In my situation, there are two classes: ...

modification of class into hooks, receiving error message 'then' property is not found in type '(dispatch: any) => Promise<void>'

As a newcomer to React hooks, I have been converting code from class components to hooks. However, I am encountering an error message when trying to use 'then' in hooks that says 'Property 'then' does not exist on type '(dispa ...

What is the significance of having nodejs installed in order to run typescript?

What is the reason behind needing Node.js installed before installing TypeScript if we transpile typescript into JavaScript using tsc and run our code in the browser, not locally? ...

Ensure that a particular key type is determined by the value of another key within the object (Utilizing Discriminated Unions)

The title of my question may not have been clear about what I am looking for, but what I need is something known as discriminated unions. You can find more information about it here: https://www.typescriptlang.org/docs/handbook/unions-and-intersections.htm ...

What could be causing eslint to generate errors for .d.ts files within my node application?

I recently set up eslint for my TypeScript node project and included a file called app.d.ts in the repository. However, when I run the linting process, I encounter the following error: error Parsing error: "parserOptions.project" has been set f ...

Exploring the Power of TextEncoding in TS 2.8 within the Angular 6 Environment

I'm facing a challenging issue while trying to import TextEncoding in TS 2.8. I have installed it using npm and attempted to import it like this: import { TextDecoder } from 'text-encoding'; Alternatively, import { } from 'text-encod ...

Having trouble retrieving information from Node.js service in AngularJS 2

I am currently expanding my knowledge of Angular and attempting to retrieve data from a node js service using Angular 2 services. When I access the node js services directly from the browser, I can see the results. However, when I attempt to fetch the dat ...

utilizing regular expressions in TypeScript

I'm currently working with Angular 2 and I have a URL link: www.abcd.com/Computers_Accessories/panache-air-pc/P-coac-20620024815-cat-z.html#newId=P-coac-41130779424?trackId=paym&subTrackId=&infitag=1234 My goal is to remove the portion #newId ...

Optimal strategies for managing request and response within an Express application

I've developed a REST API using express (and typescript) with the following structure: app.ts routes controllers models Query: Where is the ideal location to handle and construct requests/responses? Is it in routes or controllers? I am ...

Angular 10: handling undefined error even with if statement checking for null values

After fetching a product from the backend, I ensure that if it contains images, they are also loaded. This functionality is already functioning properly when images are present. However, I need to implement a conditional check to skip products without imag ...