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

150
Vistas
Is possible to produce a generic class indexed by a condition in typescript?

Suppose a scheme of validation like this :

export class User {
  @IsNotEmpty()
  id: number;
  
  @IsNotEmpty()
  name : String

  @IsNotEmpty()
  hair : String
}

And I am using this scheme for user insertion on my database, however, I want to re-use this same scheme for data updating, but neither name nor hair variables need to be not empty now.

So instead of creating a new class for that, it will be better if an index of a type in the class decides when I want both prepositions.

type Optional = ()
class Required extends Optional {}
class NotRequired extends Optional {} 
export class User<N extends Optional> {
  @validateIf(() => /* check if Optional extends for Required */)
  @IsNotEmpty()
  id: number;
  
  @IsNotEmpty()
  name : String

  @IsNotEmpty()
  hair : String
}

Basically, User<Required> will require the decorators of IsNotEmpty, and User<NotRequired> won't require the decorators.

I know that typescript can not lift type value for runtime, but maybe there is a way in pure compile-time.

about 4 years ago · Juan Pablo Isaza
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