My goal is to achieve a similar functionality in C#
. Reflection can be used in C#
to dynamically create an instance of a class based on the Type
class. The code snippet below demonstrates how this can be done in C#
:
interface IHandler
{
void Handle();
}
var handlers = new Dictionary<string, Type>
{
{ "querydom", typeof(QueryDomHandler) },
{ "other", typeof(OtherHandler) },
};
var type = handlers["querydom"];
var instance = (IHandler)Activator.CreateInstance(type, args);
instance.Handle();
How can the same be achieved using typescript
? Below is the code I have come up with, but I am unsure how to obtain the "Type" from a class (QueryDomCommandHandler
) or how to dynamically instantiate a class without explicitly referencing its name (new QueryDomCommandHandler()
).
let handlers = [];
handlers[CommandType.QueryDom] = QueryDomCommandHandler; //how can the "type" be stored?
chrome.runtime.onMessage.addListener((message: Command, sender, sendResponse) => {
logger.debug(`${isFrame ? 'Frame' : 'Window'} '${document.location.href}' received message of type '${CommandType[message.command]}'`);
const handlerType = handlers[CommandType.QueryDom];
const handlerInstance = ????? //how can the class be instantiated?
if (message.command == CommandType.QueryDom) {
const handler = new QueryDomCommandHandler(message as RulesCommand);
const response = handler.handle();
sendResponse(response);
return true;
}
else if (message.command == CommandType.Highlight) {
const handler = new HighlightCommandHandler(message as RulesCommand);
handler.handle();
}
});
Any suggestions?
UPDATE
Thank you for the responses, here is my solution. Ideally, I would like to use the enum
instead of hardcoded strings in the Record
, but I haven't been able to figure that out:
const handlers: Record<string, (new () => commands.CommandHandlerBase)> = {
'QueryDom': QueryDomCommandHandler,
'Highlight': HighlightCommandHandler,
'ClearHighlight': ClearHighlightCommandHandler,
};
const handlerType = handlers[commands.CommandType[message.command]];
const handler = new handlerType();
const response = await handler.handle(message);