1

When using yup v0.32.8 with TypeScript, we are getting the TS error message

Argument of type 'Reference' is not assignable to parameter of type 'number | Reference'. Type 'Reference' is not assignable to type 'Reference'. Type 'unknown' is not assignable to type 'number'.ts(2345)

when we attempt to use the Yup.ref() function with Yup.moreThan(), such as in this SO question that does not use TypeScript.

Why is this error being raised when using TypeScript, and how can we fix it? Thanks!

import * as Yup from 'yup';

const schema = Yup.object().shape({
    minPrice: Yup
        .number()
        .positive('Must be positive')
        .integer('Must be an integer')
        .required('Required'),
    maxPrice: Yup
        .number()
        .positive('Must be positive')
        .integer('Must be an integer')
        .moreThan(Yup.ref('minPrice'))     // <- ERROR HERE!
        .required('Required'),
})

Update:

Changing to

    maxPrice: Yup
        .number()
        .positive('Must be positive')
        .integer('Must be an integer')
        .moreThan(Yup.ref<number>('minPrice'))
        .required('Required'),

results in the error

Argument of type 'Reference' is not assignable to parameter of type 'number | Reference'. Type 'Reference' is not assignable to type 'Reference'. Type 'unknown' is not assignable to type 'number'. TS2345

Nyxynyx
  • 61,411
  • 155
  • 482
  • 830
  • 1
    Seems like this issue has been fixed with this [Pull request](https://github.com/jquense/yup/pull/1208) but it's not released yet. May be you can directly install the package from [source](https://github.com/jquense/yup) – Abdul Niyas P M Feb 13 '21 at 06:51

1 Answers1

3

You can provide a generic type to Yup.ref. It default to unknown and cause the error because moreThan expect a Reference<number>.

import * as Yup from 'yup';

const schema = Yup.object().shape({
    minPrice: Yup
        .number()
        .positive('Must be positive')
        .integer('Must be an integer')
        .required('Required'),
    maxPrice: Yup
        .number()
        .positive('Must be positive')
        .integer('Must be an integer')
        .moreThan(Yup.ref<number>('minPrice'))
        .required('Required'),
})

Update: This require a new version of yup that is still unreleased. Until it get released, you can use:

moreThan(Yup.ref<number>('minPrice') as Reference<number>)
  • Thanks! Tried your suggestion but a different error appeared. Updated the question to show the new error – Nyxynyx Feb 13 '21 at 16:27