Create a definition for the keys type of an object based on an array

I am looking for a way to dynamically assign symbols from an array called TYPES_ARR as keys in the variable TYPES_GENERATED. I want each key in TYPES_GENERATED to have a corresponding symbol value.

const TYPES_ARR = [
  'HttpClient',
  'Parser'
]
const TYPES_GENERATED = {}

TYPES_ARR.forEach(i => {
  TYPES_GENERATED[i] = Symbol.for(i)
})

Instead of explicitly defining the types like below:

const TYPES_GENERATED: {
  HttpClient: symbol
  Parser: symbol
} = {}

I found this solution on this link.

Is there a more dynamic way to achieve this using the latest version of TypeScript?

Answer №1

One approach to optimize this code is by utilizing a const assertion to enable the compiler to monitor the specific string literal values within TYPES_ARR. After that, it's recommended to confirm that TYPES_GENERATED represents a mapped type (for instance, using the predefined Record<K, V>) with keys derived from the elements of TYPES_ARR and values set as type symbol:

const TYPES_ARR = ["HttpClient", "Parser"] as const;
const TYPES_GENERATED = {} as Record<typeof TYPES_ARR[number], symbol>;
TYPES_ARR.forEach(i => {
  TYPES_GENERATED[i] = Symbol.for(i);
});

Hopefully, this suggestion proves useful for your implementation. Best of luck!

Direct link to code sample

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 should be the datatype of props in a TypeScript functional HOC?

My expertise lies in creating functional HOCs to seamlessly integrate queries into components, catering to both functional and class-based components. Here is the code snippet I recently developed: const LISTS_QUERY = gql` query List { list { ...

Enhance the Component Props definition of TypeScript 2.5.2 by creating a separate definition file for it

I recently downloaded a NPM package known as react-bootstrap-table along with its type definitions. Here is the link to react-bootstrap-table on NPM And here is the link to the type definitions However, I encountered an issue where the types are outdate ...

Limiting the defaultValue of a select to one of the values of its options in TypeScript: A guide

Is there a way to configure the Select component's properties so that the defaultValue is limited to one of the predefined options values ("au" | "nz" in this scenario)? const countryOptions = [ { value: "au", l ...

Displaying Typescript command line options during the build process in Visual Studio

As I delve into the world of VS 2015 Typescript projects, I find myself faced with a myriad of build options. Many times, the questions and answers on Stack Overflow mention command line options that I'm not completely familiar with, especially when i ...

The health check URL is experiencing issues: Unable to locate any routes

I am currently developing a .net Core 2.2/Angular 8 application and recently came across the HealthCheck feature. I decided to incorporate it into my application, so here is a snippet from my Startup.cs file: using HealthChecks.UI.Client; using Mi ...

Tips for extracting information from a TypeScript JSON document

Hey there, I'm currently having trouble understanding how to retrieve data from a JSON file. environment.ts: export const environment = { production: false, urlListBooks: "/assets/list-books.json", urlGetBooks: "/assets/edit- ...

Common problems encountered post Typescript compilation

I encountered the same problem. Below is my tsconfig settings: "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "newLine": "LF", &q ...

Enhancing class functionality with decorators in TypeScript

Over on the TypeScript's Decorator reference page, there is a code snippet showcasing how to override a constructor with a class decorator: function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) { return class extends con ...

Enhance user experience by implementing jQuery autocomplete feature to efficiently populate multiple fields using JSON data from a single

I'm currently working on integrating the jQuery autocomplete plugin with a local JSON variable as the input. My goal is to have the adjacent address fields populate automatically once the user selects an option from the autocomplete list. Below is th ...

What could be causing the Typescript error when utilizing useContext in combination with React?

I am currently working on creating a Context using useContext with TypeScript. I have encapsulated a function in a separate file named MovieDetailProvider.tsx and included it as a wrapper in my App.tsx file. import { Context, MovieObject } from '../in ...

Access arrays/objects within main object using JavaScript's Object.keys()方法

Perhaps the title is a bit confusing, but I couldn't come up with a better way to phrase it. I have a function that determines the value of each property within a contact object and returns 'No Data' if the value is null/empty/undefined. Ho ...

What is the process for moving information between files?

I have two files which are named as, employee-rates-controller.ts: private load() { return this.entityService .load(this.$scope.projectRevisionUid) .then(resp => { localStorage.removeItem('employeerates'); this.$ ...

Subclass callback with parameters

Having some trouble with one of my TypeScript functions and I'm hoping it's not a silly question. I believe what I'm attempting should work in theory. Here's a simplified version of my issue to demonstrate where the problem lies (the o ...

PHP, utilizing the mysqli function to work with arrays

I am currently learning how to work with PHP and MySQL. Within my database, I have a table named user_entries which consists of two columns: max_val and num. To extract these two columns and analyze them using the function numberTimesOver, I wrote a code ...

BarChart is failing to exhibit data in tooltips when using dynamic keys

Query Description Hello! I'm currently tackling an issue with a bar chart. Everything is working smoothly, except for the default tooltip, which appears blank when hovering over the bars. My chart utilizes dynamic keys for the legends, and they are f ...

Vue's Global mixins causing repetitive fires

In an effort to modify page titles, I have developed a mixin using document.title and global mixins. The contents of my mixin file (title.ts) are as follows: import { Vue, Component } from 'vue-property-decorator' function getTitle(vm: any): s ...

Proper Validation in Angular6: Preventing Empty Input Fields

I've been working with Angular and grappling with the challenge of validating input fields to prevent white spaces. I decided to experiment with an IF statement, as shown below. Everything seemed to be working smoothly until I encountered an error mes ...

When running `ng serve` or `ng build --prod`, the dist folder is not created in an Angular 4 application

I recently completed building an Angular 4 app using angular-cli version 1.0.4 and generated the production build with the command ng build --prod. However, I encountered a problem as the expected dist folder was not created after executing this command. ...

Do not make unnecessary calls to the server when changing the display property of an HTML object

How can I prevent a server request for the pdf file? I've experimented with using visibility=hidden and width=0. <object class='pdfClass' data='"+conventionId+"/showPdf.html' width='100%' height='600'>< ...

A guide on efficiently populating tuple values into duplicated or repeated rows using Pyspark

Below is the dataframe. +-----------+---+ | name|age| +-----------+---+ | Ashok| 23| | Jai| 45| | Kin| 12| +-----------+---+ I decided to duplicate the rows using this code snippet: df.withColumn('repeated', F.expr(&apos ...