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

119
Visualizações
Is it possible to infer generic type from inside string template literal

The following piece of code does exactly what I intend to know with one caveat, I would like to avoid having to explicit the generic it needs.

type EventGroup = {
  actions: "run" | "save"
  other: "bla"
}

export type EventType<T extends keyof EventGroup> = `${T}/${EventGroup[T]}`

const t: EventType<"actions"> = "actions/run"

I would like Typescript to infer that:

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

Which is what this code does but with an explicit generic.

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

0

You can do that with a mapped type you then take a union of the values from:

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

Testing the validity of the type:

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

Playground link

There are two parts to that, first the mapped type:

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

which evaluates as:

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

Then we use [keyof EventGroup] on the end to extract just the values of actions and other as a union.

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