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

103
Visualizações
Extract string literal union from array of classes based on constructor parameters

I am trying to get a string literal union based on values passed to an array of classes via constructor.

For example, the array looks like this:

const myArray = [
  new MyClass({
    key: "key1", 
  }),
  new MyClass({
    key: "key2", 
  }), 
]

And I'm trying to construct a mapped version of it (for lookup) or a string literal union:

type MyUnionType = "key1" | "key2"  

The primary reason for this is to ensure that any lookups use available keys assigned to the class.


getClass('key1') // all good 

getClass('notAKey') // error

However all solutions I've seen so far include some form of redundancy in either passing the key as a generic or creating an object with the same keys.

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

0

You can do something like this:

type MyUnionType = {
  [K in keyof typeof myArray]:
    (typeof myArray)[K] extends MyClass<infer T> ? T : never
}[number]

This is a mapped type that goes over each key in the array, and then infers the generic parameter from each member of myArray.

This assumes a class like:

class MyClass<T extends string> {
  constructor(options: { key: T }) {}
}

Which you would use like:

const myArray = [
  new MyClass({
    key: "key1", 
  }),
  new MyClass({
    key: "key2", 
  }), 
] as const

function getClass(input: MyUnionType) {}
getClass('key1') // works
getClass('notAKey') // error

Playground


Or, parameterized for more flexibility:

type MyUnionType<T extends readonly MyClass<string>[]> = {
  [K in keyof T]:
    T[K] extends MyClass<infer U> ? U : never
}[number]

function getClass(input: MyUnionType<typeof myArray>) {}
getClass('key1') // works
getClass('notAKey') // error

Playground

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