jquense / yup

Dead simple Object schema validation
MIT License
22.93k stars 934 forks source link

Restrict types of MessageParams.type #2131

Open olliechick opened 1 year ago

olliechick commented 1 year ago

Currently, MessageParams is defined as:

export interface MessageParams {
  path: string;
  value: any;
  originalValue: any;
  label: string;
  type: string;
  spec: SchemaSpec<any> & Record<string, unknown>;
}

This means that when using setLocale to set translatable strings to validation messages, we can't guarantee type safety. For example, I use i18next to translate strings. If I try to pass in the type like this:

setLocale({
    mixed: {
        notType: params => t('enterType', { type: t(params.type) })
    }
});

with a translation file containing:

export default {
    common: {
        enterType: 'Please enter a {{type}}',
        number: 'number',
        string: 'string',
        // more to account for all types
    }
}

it results in a type error, because it cannot guarantee that when I pass in params.type to the t function that it will result in a valid translation.

Suggested change

Change the type of type to something like this:

  type: 'string' | 'number' | //todo the rest of the possible values