Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda