Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
¿Cómo escribir una constante con funciones definidas por cadenas?

Digamos que tengo este código TypeScript:

 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);

Tengo un error con EventHandler cerca de la parte superior.

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

También tengo un error con eventName en la última línea con:

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

https://www.typescriptlang.org/play?#code/KYOwrgtgBAogajAcgFSgbwFBSgMQJIBKAysgPrxKoC8UARAOYCGEwAXAGYCWATgM4AupUAGMA9mBD9g3WgBoMAXwwYxIAbABuofgAlGIACYAbaaygBrYAE9R7KPysAHYLc3aoNTNmwBtCigA6fGIyf2QAXTMACgNGfkYzfSsASg8APnQsb2zVXlETAKNReiiAAx1gIyL7AAtpYFkoABI0WPiAgCMjMGBSRyNGK2kFUuSAbizsJSUVUTV+KDbGD3QoLp6+gaHuMwByACFu4CgAWWFDnt3G4C1JMzCgwhJyBBQlXIWb7URmNlhX6iLOKMAJfSQTDAwW66fTGaQ+MH8H4scIxYHjIA

¿Ves lo que quiero decir? ¿Cómo puedo escribir esto correctamente?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Comencemos a escribir EventHandler y resolvamos esto.

En primer lugar, es un objeto:

 type EventHandlerType = {};

Tiene claves que son EVENTOS

 // Create a mapped type mapping events to anything type EventHandlerType = { [e in EVENT]: any }

Cada valor es una función que toma un parámetro de datos y devuelve vacío

 // Create a mapped type mapping events to anything type EventHandlerType = { [e in EVENT]: (data: any) => void };

Que debería funcionar en su código:

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

Esto se simplifica con el Record de tipo de utilidad incorporado que existe para estos casos:

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

Consulte los tipos asignados en los documentos para obtener más ejemplos y un desglose.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda