Require type parameter to be of enum type

I have a specific goal in mind:

// first.ts
export enum First {
  One,
  Two,
  Three
}
// second.ts
export enum Second {
  One,
  Two,
  Three
}
// factory.ts

// For those unfamiliar, Record represents an object with key value pairs
type NotWorkingType<T> = Record<T , string>;
    

// I'm struggling to make either of these objects function properly. 
// An important note is that external enums like First and Second can be extended by adding a "Third" without any issues.

const testObject: NotWorkingType<First> = {
  [First.One]: 'first',
  [First.Two]: 'second',
  [First.Three]: 'third',
}

const testObject: NotWorkingType<Second> = {
  [First.One]: 'first',
  [First.Two]: 'second',
  [First.Three]: 'third',
}

The current issue arises here:

// Type 'T' does not satisfy the constraint 'string | number | symbol'.
// Type 'T' is not assignable to type 'symbol'.(2344)
//                              |
//                              v
type NotWorkingType<T> = Record<T , string>;

I attempted to utilize k in keyof typeof T like this as well:

type NotWorkingOtherType<T> = {
  // 'T' only refers to a type, but is being used as a value here.(2693)
  //                 |
  //                 v
  [k in keyof typeof T]: string;
}

No matter how I try to use generic parameters, it seems enums just won't cooperate.

Is there something crucial that I am overlooking?

Answer №1

TS explains the requirement that the Key in Record<Key, Value> must be of type string, number, or symbol. This is because JS object property names can only fall into one of those categories (and essentially, numbers are converted to strings behind the scenes). Therefore, it is necessary to ensure (using the extends keyword) that the T in

type NotWorkingType<T> = Record<T, string>
has the ability to be matched with the union string | number | symbol. Your use of simple enums means their values can be equated with number:

export enum First {
  One,   // First.One === 0
  Two,   // First.Two === 1
  Three  // First.Three === 2
};

type WorkingType<T extends number> = Record<T, string>;

const testObject: WorkingType<First> = {
  [First.One /* === 0 */]: "first",
  [First.Two /* === 1 */]: "second",
  [First.Three /* === 2 */]: "third",
};

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 a conditional ngIf statement in HTML or incorporating a variable within typescript for logical operations

When working with our application, we often need to display or hide a button based on specific logic. Where do you think it is best to define this logic and why? In HTML: *ngIf='logic goes here' //Or *ngIf='someBoolean' and in Type ...

In JavaScript, loop through an array of arrays and combine them using the concat

If I have an array like [["a", "b"], ["c", "d"]], is there a way to iterate, reduce, map, or join this array in order to get the desired output of ["ac", "ad", "bc", "bd"]? What if the array is structured as [["a", "b"], ["c", "d"], ["e", "f"]]; how can we ...

Troubleshooting notifications generated by react-hook-form and zod

My customer registration form is causing all my error messages to show as "required." I suspect it might be a misconfiguration in zod or react-hook-form. Below, you'll find the code snippets. This is my generic input component: import { DetailedHTMLP ...

What sets typescript apart when using a getter versus a regular function?

Imagine having a class with two methods declared for exclusive use within that class. // 1. private get something() { return 0; } // 2. private getSomething() { return 0; } While I am familiar with getters and setters, I'm intrigued to know if ther ...

Retrieve various data types through a function's optional parameter using TypeScript

Creating a custom usePromise function I have a requirement to create my own usePromise implementation. // if with filterKey(e.g `K=list`), fileNodes's type should be `FileNode` (i.e. T[K]) const [fileNodes, isOk] = usePromise( () => { ...

The S3 signature verification failed while generating a signed URL on the server-side using Node.js

Trying to upload a video file to my bucket using a pre-signed URL in angular4. Instructions: let s3 = new AWS.S3(); s3.config.update({ accessKeyId: process.env.VIDEO_ACCESS_KEY, secretAccessKey: process.env.VIDEO_SECRET_KEY }) ...

Error message: Unable to locate module when utilizing my alternative library packaged with Rollup

Currently, I am utilizing rollup to package a UI library for use across various primary applications. However, the bundled ESM file contains imports that are incompatible with webpack in the main applications: import { ArrowDropDownCircleOutlined } from &a ...

What are the steps to enable screen sharing within an Electron application?

I am currently working on developing two applications for screen sharing within a LAN setting using Electron, React, and TypeScript. The first app will capture the screen stream and broadcast it via UDP, while the second app, running on multiple devices, w ...

The node version in VS Code is outdated compared to the node version installed on my computer

While working on a TypeScript project, I encountered an issue when running "tsc fileName.ts" which resulted in the error message "Accessors are only available when targeting ECMAScript 5 and higher." To resolve this, I found that using "tsc -t es5 fileName ...

Is it possible to retrieve the child state value in the parent component using useRef in ReactJS with TypeScript (hooks)?

I am currently learning Typescript and I am trying to figure out how to pass child state values to the parent component using a ref when a button is clicked in order to update the reducer values. However, I keep running into errors when I try to pass a ref ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

Issue with Angular2/4 Module: Unable to locate 'three' in the application directory

As a newcomer to Angular and TypeScript, I am encountering difficulties when trying to import the @types/three npm package. I have created a new Angular project and attempted to use the three package, but I keep receiving the following error: Module not f ...

Is React Typescript compatible with Internet Explorer 11?

As I have multiple React applications functioning in Internet Explorer 11 (with polyfills), my intention is to incorporate TypeScript into my upcoming projects. Following the same technologies and concepts from my previous apps, I built my first one using ...

Tips on leveraging separate files for classes in TypeScript

I'm currently working on developing a TypeScript application where each class is saved in its own .ts file. I prefer to use VS Code for this project. So far, my compile task seems to be functioning correctly (transpiling .ts files into .js files). How ...

Using Cypress fixtures with TypeScript

After transitioning from using Cypress with Javascript specs to Typescript, I encountered a challenge in working with Fixtures. In Javascript, the approach below worked; however, I faced difficulties when switching to Typescript. Fixture JSON file: I sto ...

Steps to prevent closing the alert box when clicking outside of it in Ionic

I am currently developing an Ionic 2 app and I have implemented the following component: http://ionicframework.com/docs/components/#alert import { AlertController } from 'ionic-angular'; export class MyPage { constructor(public alertCtrl: Al ...

What is the best way to retrieve the final value stored?

This is how I am using my Selector:- private loadTree() { this.loading = true; this.store.select(transitionListSelector).pipe().subscribe(data => { console.log(data); data.map(item => { console.log(item); this.tr ...

Facing issue with local redis session not functioning as intended

I'm encountering an issue with my redis session not functioning properly when testing locally. EDIT: Additionally, I realized that it's failing to save a cookie when trying to set req.session[somekey] as undefined like so: req.session.user = u ...

What are the steps to set up tsline in settings.json file?

Currently utilizing visual studio code Upon searching for the settings.json file, the contents appear as follows: { "liveServer.settings.donotVerifyTags": true, "liveServer.settings.donotShowInfoMsg": true, "javascript ...

Tips for efficiently finding and comparing text within the results generated by a for loop in Angular/Javascript

In my XML data, I have extracted all the tag names using a for loop and some other logic. Now, I am looking to find the word 'author' from the output values that are displayed in the console during the loop. If any of the output values match &apo ...