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

179
Visualizações
Get values of Generic argument extending array

Is it possible to retrieve the values of a generic type that extends, e.g., string[]? My use case is to check whether a given value is included in this "array":

function isC<C extends string[]>(attribute: string): attribute is C[number] {
  const valueSet: Set<string> = new Set(C)
  return valueSet.has(attribute)
}
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

TypeScript's type system is erased when TypeScript is compiled to JavaScript, and the JavaScript is what actually runs. Your function therefore compiles to

function isC(attribute) {
    const valueSet = new Set(C); // <-- this C doesn't exist
    return valueSet.has(attribute);
}

And that's the problem the compiler is warning you about. There is no such thing as C in your JavaScript code. C is just a type, and that type is not present at runtime. In order for this to make any sense at runtime, you need to have a value of type C. Possibly like this:

function isC<C extends string[]>(attributes: [...C], attribute: string): attribute is C[number] {
    const valueSet: Set<string> = new Set(attributes)
    return valueSet.has(attribute)
}

And that will work:

let attr = Math.random() < 0.5 ? "b" : "d";
if (isC(["a", "b", "c"], attr)) {
    console.log({ a: 1, b: 2, c: 3 }[attr]);
} else {
    console.log("nope");
}

Note, though, that the particular implementation can probably be tweaked. There's no reason why you need to keep track of the actual array type, you just want the string literal types of the elements. And putting all elements from the array into a Set and then doing a has() is overkill, since you can stop inspecting the array as soon as you find the element in question. Therefore I'd suggest:

function isC<C extends string>(cArray: C[], attribute: string): attribute is C {
    return (cArray as readonly string[]).includes(attribute);
}

Which also works.

Playground link to code

about 4 years ago · Santiago Trujillo 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