Yup conditional validation and TypeScript

Viewed 2244

Given the following interface and corresponding Yup schema. Is there a way for TypeScript to automatically infer the conditional function arguments (e.g. enabled and schema)?

import { object as yupObject, string as yupString, boolean as yupBoolean } from 'yup';

interface Foo {
    enabled: boolean
    name?: string
}

const fooSchema = yupObject().shape({
    enabled: yupBoolean(),
    name: yupString().when('enabled', (enabled, schema) => enabled ? schema.required() : schema)
})

I've tried yupObject()<Foo> and shape<Foo>(..) but neither helped. If it can't be done automatically, what is the appropriate type for schema in this case?

2 Answers

Can you try something like this

import * as Yup from "yup"

interface Foo {
    enabled?: Yup.BooleanSchema
    name?: Yup.StringSchema
}

const FooSchemaObj: Foo = {
    name: Yup.string().when('enabled', (enabled, schema) => enabled ? 
             schema.required() : schema),
    enabled: Yup.boolean() 
}

What worked for me was something like this:

import * as Yup from 'yup';
import { SchemaOf, StringSchema } from 'yup';

interface Foo {
  enabled: boolean;
  name?: string;
}

const FooSchemaObj: SchemaOf<Foo> = Yup.object({
  enabled: Yup.boolean(),
  name: Yup.string().when('enabled', (enabled: boolean, schema: StringSchema) =>
    enabled ? schema.required() : schema
  )
});

I managed to get typescript to work with the first param and schema property, but not automatically sadly.

Related