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

102
Views
Tipo de retorno de mecanografiado para objeto dinámico anidado

Supongamos que hay una función que devuelve el siguiente objeto.

 private static prepareExperienceFilter(experienceLevel: ExperienceFilterType): any { const aggregationObject = { 'lt_1': { $lt: 1 }, 'between_1_3': { $gt: 0, $lt: 3 }, 'between_3_5': { $gt: 2, $lte: 5 }, 'gt_5': { $gt: 5 } }; const condition = aggregationObject[experienceLevel]; return { 'yearsOfExperience.min': condition }; }

¿Cómo podemos definir un tipo o interfaz para tal objeto?

He intentado tipos de unión, pero no tuve éxito.

Gracias por cualquier ayuda.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Al mover el objeto estático fuera de su método, puede hacer referencia a su tipo en el tipo de retorno de la función. Esto le permitirá usar un parámetro de tipo genérico para restringir el parámetro de función (al tiempo que proporciona una inferencia de IntelliSense al desarrollador que lo usa) e indexar el tipo de retorno:

Parque infantil TS

 const aggregationObject = { 'lt_1': { $lt: 1 }, 'between_1_3': { $gt: 0, $lt: 3 }, 'between_3_5': { $gt: 2, $lte: 5 }, 'gt_5': { $gt: 5 }, }; type ExperienceFilterType = keyof typeof aggregationObject; function prepareExperienceFilter <T extends ExperienceFilterType>(experienceLevel: T): { 'yearsOfExperience.min': typeof aggregationObject[T]; } { const condition = aggregationObject[experienceLevel]; return { 'yearsOfExperience.min': condition }; } const result_lt_1 = prepareExperienceFilter('lt_1'); // { 'yearsOfExperience.min': { $lt: number; }; } const result_gt_5 = prepareExperienceFilter('gt_5'); // { 'yearsOfExperience.min': { $gt: number; }; } const result_invalid = prepareExperienceFilter('another_key'); /* ~~~~~~~~~~~~~ Argument of type '"another_key"' is not assignable to parameter of type '"lt_1" | "between_1_3" | "between_3_5" | "gt_5"'.(2345) */
about 4 years ago · Juan Pablo Isaza Report
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!