Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!