Utilizing a map in conjunction with template literal types results in an error being thrown

I am currently working on implementing the documentation provided here.

This is the code snippet I have:

enum InputFieldName {
    ReactionsCheckbox = 'reactionsEnabled',
    SettingsCheckbox = 'settingsEnabled',
}
type PropEventSource<Type> = `${string & keyof Type}Checkbox`;

const inputMap: Record<InputFieldName, PropEventSource<InputFieldName>> = {
    [InputFieldName.ReactionsCheckbox]: 'reactionsEnabledCheckbox',
    [InputFieldName.SettingsCheckbox]: 'settingsEnabledCheckbox',
}

const fieldName = inputMap[InputFieldName.ReactionsCheckbox]

console.log('fieldName', fieldName);

Although I am able to see ‘reactionsEnabledCheckbox’ in the console correctly, I am encountering a TypeScript error:

Type of computed property's value is '"settingsEnabledCheckbox"',
  which is not assignable to type '"charAtCheckbox" | "charCodeAtCheckbox"
    | "concatCheckbox" | "indexOfCheckbox" | "lastIndexOfCheckbox"
        | "localeCompareCheckbox" | "matchCheckbox" | "replaceCheckbox" | ... 33 more ... | "valueOfCheckbox

Can anyone provide guidance on how to resolve this issue?

Furthermore, it seems like prettier is not recognizing the following line as valid code:

type PropEventSource<Type> = `${string & keyof Type}Checkbox`;

Answer №1

If your enum InputFieldName contains values of type string, you can directly use the enum type in your template literal type (`${string & Type}Checkbox`) instead of using keyof InputFieldName.

It's worth noting that you can always incorporate an enum in a template literal type, like type Permutations = `${MyEnum}`;. You only need to intersect it with string (= & string) because the generic parameter Type has no constraint.

enum InputFieldName {
  ReactionsCheckbox = "reactionsEnabled",
  SettingsCheckbox = "settingsEnabled",
}
type PropEventSource<Type> = `${string & Type}Checkbox`;

const inputMap: Record<InputFieldName, PropEventSource<InputFieldName>> = {
  [InputFieldName.ReactionsCheckbox]: "reactionsEnabledCheckbox",
  [InputFieldName.SettingsCheckbox]: "settingsEnabledCheckbox",
};

const fieldName = inputMap[InputFieldName.ReactionsCheckbox];

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

How can I enable editing for specific cells in Angular ag-grid?

How can I make certain cells in a column editable in angular ag-grid? I have a grid with a column named "status" which is a dropdown field and should only be editable for specific initial values. The dropdown options for the Status column are A, B, C. When ...

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

lines stay unbroken in angular

I am encountering an issue when I execute the following code: DetailDisplayer(row) : String { let resultAsString = ""; console.log(row.metadata.questions.length); (row.metadata.questions.length != 0 )?resultAsString += "Questions ...

Exploring Angular: The Dynamic Declaration of object.property in ngModel

<input [(ngModel)]="Emp."+"dt.Rows[0]["columnname"]"> This scenario results in an undefined value In my current project, I am leveraging the power of a MVC CustomHtmlHelper to generate textboxes dynamically based on database schema. The textbox ...

Grab a parameter from the URL and insert it into an element before smoothly scrolling down to that

On a button, I have a URL that looks like this: www.mywebsite.com/infopage?scrollTo=section-header&#tab3 After clicking the button, it takes me to the URL above and opens up the tab labeled tab3, just as expected. However, I would like it to direct m ...

The argument labeled as 'State' cannot be assigned to a parameter labeled as 'never'

I've recently delved into using TypeScript with React. I attempted to incorporate it with the React useReducer hook, but I hit a roadblock due to an unusual error. Below is my code snippet: export interface ContractObj { company: string; ...

The elixir-typescript compilation process encountered an error and was unable to complete

I am currently working on integrating Angular2 with Laravel 5.2 and facing an issue with configuring gulp to compile typescript files. Below is a snippet from my package.json file: { "private": true, "scripts": { "prod": "gulp --production", ...

Using TypeOrm QueryBuilder to establish multiple relations with a single table

Thank you for taking the time to read and offer your assistance! I am facing a specific issue with my "Offer" entity where it has multiple relations to "User". The code snippet below illustrates these relationships: @ManyToOne(() => User, (user) => ...

Reasons why a functional component may not trigger a rerender after a state change using useReducer()

When using react Hooks, specifically useReducer, I found that although the state changes, the functional component does not rerender. Additionally, when trying to open the drawer by pressing a button in the menu, even though the state changes the drawer re ...

Having trouble getting the React form validation to work using Material UI TextField and TypeScript

I'm having trouble implementing validation on a "sign up" page using the MUI library in React with TypeScript. I've added the "required" attribute to each TextField tag, but the validation doesn't seem to be working upon submission. I'v ...

Using Angular 2, NodeJS, and Mongoose to send data from an Angular 2 frontend to a NodeJS backend REST API. However, encountering an issue where the Node API logs show that the OPTIONS

I am facing an issue with sending data from my Angular2 frontend API to the backend client, which is built using NodeJS and mongoose. When I inspect the data being sent on the Angular2 client through console.log, I can see that the correct values are being ...

Attempting to utilize a default import to invoke an expression that does not have a call signature is not

I am currently experimenting with using https://github.com/arnaudbenard/redux-mock-store in conjunction with TypeScript. I have gone ahead and installed @types/redux-mock-store which includes the necessary export default createStore statement. In my attem ...

What is the best way to incorporate this in a callback function?

Utilizing a third-party component requires creating an object for configuration, such as itemMovementOptions in the given code sample. export class AppComponent implements OnInit { readonly itemMovementOptions = { threshold: { horizontal: ...

I am in need of assistance with incorporating a particular hibernate Inheritance mapping into my project

I am dealing with a situation where I have two classes, parent and child, with a self-referential relationship on the child side. The database is set up with separate tables for both parent and child, sharing the same "id", and using the column "holder" as ...

Validation of Single Fields in Angular Reactive Forms

When I validate a reactive form in Angular, I expect the error message to show up beneath the invalid field whenever incorrect data is entered. <form (ngSubmit)=sendQuery() [formGroup]="form"> <div *ngFor='let key of modelKeys&ap ...

Attempting to transfer files to and from Firebase storage

Having trouble with my React Native app. I am trying to upload files, whether they are pictures or PDFs, but once uploaded, I can't seem to open them. However, "The files are getting uploaded to the storage." export const uploadToStorage = async (docu ...

In Angular 5 HTTP GET request, the value "null" is being converted to ""null""

I'm currently in the process of transitioning our application from Angular 4 to Angular 5. In Angular 5, when passing an object model as parameters, if one of the values is null, it gets converted to a "null" string which is causing issues for us. Her ...

The JsonFormatter is throwing an error because it is trying to access the property 'on' of an undefined variable

I have encountered an error while attempting to generate an HTML report using cucumber-html-reporter The error message is: Unhandled rejection TypeError: Cannot read property 'on' of undefined at new JsonFormatter (C:\path-to-project\ ...

Issues arise with the escape key functionality when attempting to close an Angular modal

I have a component called Escrituracao that handles a client's billing information. It utilizes a mat-table to display all the necessary data. When creating a new bill, a modal window, known as CadastrarLancamentoComponent, is opened: openModalLancame ...

What is the rationale behind assigning a random value to the `(keyup)` event in order to update template local variables in Angular2?

To update #box in <p>, I need to give a random value to the (keyup) attribute. Here's an example: <!-- The value on the right of equality sign for (keyup) doesn't matter --> <input #box (keyup)="some_random_value" placeholder ...