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