Convert C# delegate into TypeScript

Sample C# code snippet:

enum myEnum
{
    aa = 0,
    bb,
    cc,
}

public delegate void MyDelegate(myEnum _myEnum, params object[] _params);

public Dictionary<myEnum , MyDelegate> dicMyDelegate = new Dictionary<myEnum , MyDelegate>();

public void GameDelegate(myEnum _myEnum, MyDelegate _Func)
{
    if(dicMyDelegate.ContainsKey(_myEnum))
    {
        MyDelegate Func;
        dicMyDelegate.TryGetValue(_myEnum, out Func);
        Func += _Func;
    }
    else
    {
        dicMyDelegate.Add(_myEnum, _Func);
    }
}

public void GameCallBack(myEnum _myEnum)
{
    if(!dicMyDelegate.ContainsKey(_myEnum)) return;
    MyDelegate Func;
    dicMyDelegate.TryGetValue(_myEnum, out Func);
    if(Func == null) return;
    Func(_myEnum);
}

==================================================

Syntax for using delegates and dictionaries in cocos creator TypeScript.

public delegate void MyDelegate(myEnum _myEnum, params object[] _params);

public Dictionary<myEnum , MyDelegate> dicMyDelegate = new Dictionary<myEnum , MyDelegate>();

Attempting to convert the above C# code to TypeScript has been challenging.

I have been researching online resources all day for guidance.

declare module "Delegate"
{   
    export function MyDelegate(_myEnum: myEnum , args: any[]) : void;
}

import {MyDelegate} from 'Delegate';

Answer №1

When it comes to JavaScript and TypeScript, functions hold a special status as first class citizens, eliminating the need for solving problems in the same manner as you would in C#.

function example(name: string) : string {
    return 'Hello ' + name;
}

function acceptsFunction(func: Function) {
    // Executing the function passed as an argument
    const result = func('Steve');
    console.log(result);
}

// Invoking a function while passing another function as an argument
acceptsFunction(example);

In the scenario mentioned above, you have the flexibility to pass a function as an argument and call it with parameters without any added complexity.

To enhance type safety, you can specify the type of function that needs to be passed:

function acceptsFunction(func: (name: string) => string) {

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

The references to the differential loading script in index.html vary between running ng serve versus ng build

After the upgrade to Angular 8, I encountered a problem where ng build was generating an index.html file that supported differential loading. However, when using ng serve, it produced a different index.html with references to only some 'es5' scri ...

Comparing the installation of TypeScript on Ubuntu utilizing npm versus native packages (via apt)

I'm looking to incorporate Typescript into my Ubuntu system and have come across two different methods to do so: Using sudo apt update && sudo apt install node-typescript -y Running sudo npm install -g typescript My main question revolves ar ...

Mastering Angular: Accessing undefined properties (specifically 'push')

Currently, I am in the process of learning Angular and have encountered an issue while working on an assignment. The error message that I am facing is "Cannot read properties of undefined (reading 'push')." Despite knowing that this is a common e ...

Strategies for evaluating a Promise-returning imported function in Jest

I am currently facing an issue with a simple function that I need to write a test for in order to meet the coverage threshold. import { lambdaPromise } from '@helpers'; export const main = async event => lambdaPromise(event, findUsers); The ...

I'm having trouble retrieving the information as it is showing as undefined. Can anyone offer any advice?

Attempting to extract specific information from an API response has proven challenging. Despite my efforts to isolate the desired data, all listed details appear as undefined. import { HttpClient } from '@angular/common/http'; import { Injectable ...

Tips for accessing the following element within an array using a for loop with the syntax for (let obj of objects)

Is there a way to access the next element in an array while iterating through it? for (let item of list) { // accessing the item at index + 1 } Although I am aware that I could use a traditional for loop, I would rather stick with this syntax. for (i ...

Why does the property of {{hero.name}} function properly in a <h> tag but not in an <img> tag?

Within this template, the code below functions correctly: <h3>{{hero.name}}</h3> It also works for: <a routerLink="/details/{{hero.id}}">{{hero.name}}</a> However, there seems to be an issue with the following image path ...

Issues with multiple validators in Angular 8 intricately intertwined

I'm facing an issue with a reactive form control that has multiple validators. Despite defining the validation methods, the form is not being validated as expected. Below is the code snippet illustrating my attempted solutions. Method 1: civilIdNumbe ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

Which TypeScript AsyncGenerator type returns a Promise?

I am currently in the process of assigning a return type to the function displayed below: async function *sleepyNumbers() { // trying to determine TypeScript type let n = 0; while (true) { yield new Promise(resolve => resolve(n++)); ...

What are the steps to establish a class structure using deserialized JSON data?

I am struggling to create a C# class for the returned JSON data that I have. It seems like I cannot correctly map it based on the JSON structure I am working with. Even after attempting to use the "Paste Special -> Paste Json as classes" feature in Vis ...

Guide to adding a loading spinner into your Angular project

I've been attempting to incorporate a spinner into my application, but unfortunately, the spinner isn't showing up. Despite checking the console and terminal for errors, there doesn't seem to be any indication as to why the spinner is not a ...

How can I import a node-js dependency into my webpack project when the package already comes with type definitions included?

Don't bother using the deprecated @types/chalk package because the chalk library already has type definitions included. But I keep encountering the error message TS2307: Cannot find module 'chalk'. https://i.sstatic.net/uDIJi.png The proje ...

"Utilizing jQuery and Bootstrap 4 in TypeScript, attempting to close modal window using jQuery is not functioning

Trying to make use of jquery to close a bootstrap modal within an angular project using typescript code. The following is the code: function call in html: (click)="populaterfpfromsaved(i, createSaved, createProp)" createSaved and createProp are local ...

Error: Unable to locate 'v8' in NextJS when using Twin Macro

I am encountering the error message Module not found: Can't resolve 'v8' when using a package in Nextjs with TypeScript. If I use a .js file, everything works fine. However, when I switch to a .tsx file, it throws a Module Not found error. ...

Declaring a sophisticated array as a property within another property in Typescript

As a newcomer to Angular and Typescript, I am facing a challenge while declaring a property with a complex array as one of its values. Here is what I have attempted: groupedItem: { customGroupId: string, cgName: string, category: [{ cu ...

React: Implement a feature to execute a function only after the user finishes typing

Currently, I am using react-select with an asynchronous create table and have integrated it into a Netsuite custom page. A issue I am facing is that I would like the getAsyncOptions function to only trigger when the user stops typing. The problem right now ...

"I'm looking for a way to display the validation summary text in a custom alert using ASP.NET. Can anyone help with

For a recent project at school, I have been tasked with creating an ASP website. One of the features on the login form is several validators and a validation summary. Although the validation summary itself is working correctly, I am looking to extract the ...

Utilizing TypeScript to enhance method proxying

I'm currently in the process of converting my JavaScript project to TypeScript, but I've hit a roadblock with an unresolved TypeScript error (TS2339). Within my code base, I have a class defined like this: export const devtoolsBackgroundScriptCl ...

Error Message in Terminal When Launching React Application Using Webpack

I am encountering several errors in the node terminal while attempting to launch my react-app [at-loader] ./node_modules/@types/webpack/index.d.ts:23:16 TS2665: The module name in augmentation is invalid. Module 'webpack/lib/dependencies/HarmonyE ...