What is the process for inputting a fixed value using functions defined by strings?

Imagine you have the following TypeScript snippet:

enum EVENT {
  FIRST_EVENT = "game:first_encounter",
}

const EventHandler: keyof typeof EVENT = {
    [EVENT.FIRST_EVENT]: (data: any) => {
        console.log(`Hello there, ${data.blue_player}`);
    }
}

const data = { blue_player: 'Blue McBlue', event: EVENT.FIRST_EVENT}
const eventName: EVENT = data.event;

EventHandler[eventName](data);

An issue arises with EventHandler at the top.

Type '{ "game:first_encounter": (data: any) => void; }' is not assignable to type '"FIRST_EVENT"'

Another error occurs with eventName on the last line stating:

Element implicitly has an 'any' type because index expression is not of type 'number'

If you are curious about a solution, check out this link: Click here

Do you see what's going on? How can I properly define the types in this code?

Answer №1

Let's dive into the world of EventHandler and solve this puzzle together.

Firstly, it's crucial to understand that it manifests as an object:

type EventHandlerType = {};

Each key within it corresponds to different EVENTS:

// Defining a mapped type that links events to any value
type EventHandlerType = { [e in EVENT]: any }

Every entry is essentially a function that takes a data input and outputs void:

// Establishing a mapped type relating events to values with specific functions
type EventHandlerType = { [e in EVENT]: (data: any) => void };

This structure seamlessly integrates into your project code:

const EventHandler: { [key in EVENT]: (data: any) => void } = {
    [EVENT.FIRST_EVENT]: (data: any) => {
        console.log(`Greetings, ${data.blue_player}`);
    }
}

To simplify this process, leverage the utility type Record tailored for such scenarios:


const EventHandler: Record<EVENT, (data: any) => void> = {
    [EVENT.FIRST_EVENT]: (data: any) => {
        console.log(`Greetings, ${data.blue_player}`);
    }
}

Refer to mapped types in the documentation for additional examples and detailed insights.

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 the size of the font in a <div> be adjusted based on the number of characters present?

I am attempting to create a basic HTML and CSS layout with two div blocks, each 1000px wide, within a parent container that is 3000px wide. <div class="blocks"> <div class="block-a">text 1</div> <div class="block-b">text 2& ...

Issue with Heroku deployment: unable to locate JavaScript file

I encountered an issue while deploying my node.js app. Everything seemed to be working fine but it couldn't locate the JavaScript files. The error message displayed was: proove.herokuapp.com/:16 GET 404 (Not Found) Here is the server.js code snip ...

"Customize your search experience with a bootstrap search bar featuring multiple input fields

Currently working on a website using Bootstrap and trying to create a filter bar for the items displayed on the page. I am looking to include one or more input fields (highlighted in red) and one or more dropdowns (highlighted in blue). The width of the ba ...

Loop through the JSON data to obtain distinct values for certain indices

My PHP script retrieves data with the following query: SELECT objective,signal_type,signal_name FROM signals WHERE channel="Email" This is how the data is returned: [ { "objective": "Awareness", "signal_type": "Efficiency", " ...

What is the best way to save and retain cache data for an audio file?

I have a website where I am using an audio file in .swf format. This audio file can be turned on and off with the options provided: AUDIO ON and AUDIO OFF. However, I am facing the issue that the audio keeps playing repeatedly even after being turned off. ...

Learn how to implement pagination in your React Native app by utilizing the orderByChild, equalTo, and endBefore functions in a Firebase

I am currently developing a pagination feature that loads more data based on category type. However, I have encountered an issue: endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo). I understand that I can't ...

Executing the calling statement once all function statements have been completed

I am currently working on a lengthy function that involves retrieving data from multiple levels of a database. getResult() { this.appService .getCountries() .subscribe( (countries: Country[]) => { this.countries = co ...

Best practices for utilizing dotenv / .env to pass parameters in typescript

I am currently working on a typescript application in VS Code and have moved sensitive information to a .env file: # .env file NAME='foobar' Within my main app, which utilizes the .env file, I have included the dotenv npm package. Additionally, ...

Creating a fresh occurrence of a variable type in JavaScript

How can I create a new instance of variable types in JavaScript? For example: var UserControl = { Id: '', Location: { Left: 0, Top: 0, Width: 0, Height: 0 }, Contents: '', Name: '' }; I want to store this UserControl in a J ...

Tips for altering the color of the MUI table sort label icon:

Does anyone know how to change the color of the table sort label icon from gray to red? I am having trouble figuring it out. Any recommendations or suggestions would be greatly appreciated. Here is the code I have been trying to work with: <TableSortL ...

Incorrect conditions when attempting to compare text strings

My current code retrieves the user's locale and saves it in a variable. I have implemented a conditional statement that checks if the locale matches a specific value - as shown in the image below: https://i.sstatic.net/ASVZ8.png In the screenshot, y ...

Nodejs script designed to efficiently download all files from an FTP server to a local directory before seamlessly transferring them to another FTP folder

I am currently facing a challenge in downloading all files from a specific folder on an FTP site. The folder, named "IN" (as demonstrated in the example code), contains several .csv files. The requirements for this task are: Download all CSV files presen ...

Transitioning from checkbox to input field and updating the button through Ajax in a WordPress site

Is it possible to change a checkbox with only 2 values (0 and 1) into an input field where I can enter date and time, and then update it using a submit button with Ajax? Can someone please help me convert the checkbox to an input field and add an update b ...

Evaluating the functionality of express.js routes through unit testing

Just dipping my toes into the world of express and unit testing. Take a look at this code snippet: const express = require('express'); const router = express.Router(); const bookingsController = require("../controllers/bookings"); router .r ...

What could be causing the issue with my Mongoose One-To-Many Relationships not linking correctly?

Can anyone shed light on why the connection between "users" and "posts" (where users can have multiple posts) is failing to work properly? Despite setting up my mongoose associations correctly, when a new post is made, it doesn't get assigned to a use ...

Error: Cloudant encountered a problem processing your request

Why is my attempt to upload JSON objects into a Cloudant database resulting in a "400 bad request" error? pos = { 'lat': position.coords.latitude, 'long' : position.coords.longitude }; $.ajax({ type: "POST", ...

I rely on JqTouch for my mobile web development, but I've noticed a strange behavior: whenever I refresh a page that isn't the homepage and then navigate back,

One scenario to consider is as follows: #HOME - #Page1 #Page1 - #Page2 #Page2 - #Page3 Imagine being on #Page3, refreshing the page does not alter the current position. However, if you click the back button, it redirects you to #HOME instead of #Page2. ...

Is there a way to display an animation when a page loads using jQuery that only plays for index.php and not other_page.php?

How can I trigger an animation on page load, specifically for my index.php page and not all other pages on my website? Is there a jQuery function that targets only the index.php page like this: $('index.php').ready(function()); If not, what i ...

Issue with Node.js connection to MySQL database resulting in timeout error (ETIMEDOUT)

I am attempting to establish a basic connection to an online mysql database using a node.js server. Here is the code I have written for this purpose: var mysql = require('mysql'); var con = mysql.createConnection({ host: 'example.org& ...

Optimal method for managing errors in Flask when handling AJAX requests from the front end

I'm currently working on a React application that communicates with a Python Flask server. One of the features I am adding allows users to change their passwords. To do this, an AJAX request is sent from React to Flask, containing both the old and ne ...