1

I'm developing a Typescript client for retrieving currency exchange rates.
I have these interfaces:

    export interface BaseRequestParams {
        lang?: Lang
        output?: MediaType
        path?: string
    }

    export interface DailyRatesRequestParams extends BaseRequestParams {
        referenceDate: string // Format: YYYY-MM-DD
        baseCurrencyIsoCodes: Array<keyof typeof currencies>
        currencyIsoCode: 'EUR' | 'USD' | 'ITL'
    }

and the corresponding validators are the following:

export const BaseRequestParamsValidator: Joi.ObjectSchema<BaseRequestParams | DailyRatesRequestParams> = Joi.object({
  lang: Joi.string()
           .allow('en', 'it')
           .insensitive()
           .default('en'),
  output: Joi.string()
              .allow(Object.values(MediaType).join(','))
              .default(MediaType.JSON),
  path: Joi.when('output', {
    not: MediaType.JSON,
    then: Joi.string().required(),
    otherwise: Joi.string(),
  }),
});

// eslint-disable-next-line max-len
export const DailyRatesRequestParamsValidator: Joi.ObjectSchema<DailyRatesRequestParams> = BaseRequestParamsValidator.keys({
  referenceDate: Joi.string()
                    .required()
                    .pattern(new RegExp(/(\d){4}-(\d){2}-(\d){2}/)),
  baseCurrencyIsoCodes: Joi.string()
                           .allow(Object.keys(currencies).join(','))
                           .required(),
});

It basically works, especially at runtime, but as you can see I've specified a union type for BaseRequestParamsValidator in order to have the autocomplete on the derived types. However, this is not properly correct, since the basic type shouldn't include the other types, just the very three fields I've specified there.
The question is similar to this one, except for Typescript usage. Is there a better way to specify the validator types (aka the Joi.ObjectSchema)? Thanks!

Chris
  • 1,140
  • 15
  • 30

0 Answers0