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

169
Visualizações
Define a Typescript Interface Value as either a set of strings or whatever was passed as an argument

I am not sure if I phrased the question title correctly - I am working on react components in a library that have a certain set of predefined values for some of the properties. But on a per usage basis, additional values need to be added to the interface. This works well so far:

export interface CompProps<Variant = string> {
  variant?: 'banana' | 'strawberry' | Variant;
}

I noticed though, that when working with the component, it will now accept any string for the variant property and the IDE will also not suggest these predefined values under certain circumstances.

What is the proper way to go about this?

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

0

Perhaps you could take advantage of the default type parameter to type the variant property more strongly, since it is currently 'banana' | 'strawberry' | string by default.

If you set the default parameter to never instead, you could avoid union with the general string, effectively enforcing variant to be either 'banana' or 'strawberry', which should give the IDE a stronger hint about the desired value. Here I've also added a constraint such that the variant is a string, which I assume is what you want.

If one were to set the Variant type parameter, they could explicitly state which strings they expect to pass like so:

export interface CompProps<Variant extends string = never> {
  variant?: 'banana' | 'strawberry' | Variant;
}

const test: CompProps<'chocolate'> = {variant: 'chocolate'};

With this solution however, the component will still have to accommodate the most general type (i.e. CompProps), so it most likely won't be very beneficial if the predefined values need to be apparent within the component.

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