J Krbaio
J Krbaio

Reputation: 5

Vee-validate 3.0 configure defaultMessage with vue-18n and TS

I'm trying to define the vee-validate configure object,defaultMessage in TS. I have seen this code in the examples, vee-validate.js file:

configure({
  defaultMessage: (field, values) => {
    // override the field name.
    values._field_ = i18n.t(`fields.${field}`);

    return i18n.t(`validation.${values._rule_}`, values);
  }
});

I try to convert in TS

const dm: string | ValidationMessageGenerator | undefined =
    (field: string, values: Record<string, any>) => {
        values._field_ = i18n.t(`fields.${field}`);
        return (i18n.t(`validation.${values._rule_}`, values)) as string | ValidationMessageGenerator;
    };
configure({
    defaultMessage: dm,
});

But, I try to type, I always have this Errors:

El tipo '(field: string, values: Record<string, any>) => ValidationMessageTemplate' no se puede asignar al tipo 'string | ValidationMessageGenerator | undefined'. El tipo '(field: string, values: Record<string, any>) => ValidationMessageTemplate' no se puede asignar al tipo 'ValidationMessageGenerator'. Los tipos de parámetros 'values' y 'params' no son compatibles. El tipo 'Record<string, any> | undefined' no se puede asignar al tipo 'Record<string, any>'. El tipo 'undefined' no se puede asignar al tipo 'Record<string, any>'.ts(2322)

The only configuration which works for me is to set the flags //@ts-ignore and use the javascript code, works, but I would like to type it and remove the flag

Thanks

Upvotes: 1

Views: 420

Answers (1)

logaretm
logaretm

Reputation: 1435

You don't need to have all this casting, you should read the typings carefully as there as some subtle differences, this should work:

const dm = (field: string, values: Record<string, any> = {}) => {
  values._field_ = i18n.t(`fields.${field}`);

  return (i18n.t(`validation.${values._rule_}`, values));
};

configure({
  defaultMessage: dm,
});

You were missing that values is optional and is not actually required by the ValidationMessageGenerator type, because not all rules have parameters.

Upvotes: 1

Related Questions