Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
¿Es posible inferir un tipo genérico desde el literal de la plantilla de cadena interna?

El siguiente fragmento de código hace exactamente lo que pretendo saber con una advertencia: me gustaría evitar tener que explicitar el genérico que necesita.

 type EventGroup = { actions: "run" | "save" other: "bla" } export type EventType<T extends keyof EventGroup> = `${T}/${EventGroup[T]}` const t: EventType<"actions"> = "actions/run"

Me gustaría que Typescript infiriera que:

 `actions/run` -> valid `actions/save` -> valid `actions/bla` -> NOT valid `other/bla` -> valid

Que es lo que hace este código pero con un genérico explícito.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede hacer eso con un tipo asignado y luego tomar una unión de los valores de:

 export type EventType = { [Key in keyof EventGroup]: `${Key}/${EventGroup[Key]}` }[keyof EventGroup];

Prueba de la validez del tipo:

 const t1: EventType = "actions/run"; // valid const t2: EventType = "actions/save"; // valid const t3: EventType = "actions/bla"; // NOT valid const t4: EventType = "other/bla"; // valid

Enlace del patio de recreo

Hay dos partes en eso, primero el tipo mapeado:

 type EventType = { [Key in keyof EventGroup]: `${Key}/${EventGroup[Key]}` }

que evalúa como:

 type EventType = { actions: "actions/run" | "actions/save"; other: "other/bla"; }

Luego usamos [keyof EventGroup] al final para extraer solo los valores de las actions y other como una unión.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!