Home > OS >  Typescript return type for nested dynamic object
Typescript return type for nested dynamic object

Time:03-13

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.

CodePudding user response:

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) */

  • Related