jquense / yup

Dead simple Object schema validation
MIT License
22.94k stars 935 forks source link

cannot extend locales with custom messages for new validators #2172

Closed cellog closed 9 months ago

cellog commented 10 months ago

Describe the bug when adding a new custom validator, for example a string validator that validates a BSON id, it's simple to extend StringSchema. However, because of the way that the locale object is defined using typeof (https://github.com/jquense/yup/blob/master/src/locale.ts#L156) it is not possible to extend its type to allow localizing error messages for that new validator.

To Reproduce

make a .d.ts file and put it in a path where TS will pick it up. Attempt to override the locale

import type {
  ArrayLocale,
  BooleanLocale,
  DateLocale,
  MixedLocale,
  NumberLocale,
  ObjectLocale,
  TupleLocale,
} from "yup/lib/locale";
import type { AnyObject, Flags, Maybe, Message, Schema } from "yup_v1";

declare module "yup" {
  interface StringSchema<
    TType extends Maybe<string> = string | undefined,
    TContext = AnyObject,
    TDefault = undefined,
    TFlags extends Flags = "",
  > extends Schema<TType, TContext, TDefault, TFlags> {
    bsonid(idString: string): this;
  }

  interface StringLocale {
    bsonid?: Message;
  }
  interface LocaleObject {
    mixed?: MixedLocale;
    string?: StringLocale;
    number?: NumberLocale;
    date?: DateLocale;
    boolean?: BooleanLocale;
    object?: ObjectLocale;
    array?: ArrayLocale;
    tuple?: TupleLocale;
  }
  declare const _default: LocaleObject;
}

image

Expected behavior

It should be possible to override these types

Platform (please complete the following information): all

Additional context

jquense commented 9 months ago

I wouldn't override the yup types, since yup doesn't know about your additions anyway, instead i'd just extend the type locally and you can use your MyAppLocale extends Locale in your custom tests