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

97
Views
Typescript return type for nested dynamic object

Suppose there is a function which return the following object.

 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 };
}

How we can define a type or interface for such object?

I've tried union types, but not succeeded.

Thanks for any help.

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

0

By moving the static object outside your method, you can reference its type in the function's return type. This will allow you to use a generic type parameter to constrain the function parameter (while also providing IntelliSense inference to the developer using it) and index the return type:

TS Playground

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!