Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup conditional validation and TypeScript

Tags:

typescript

yup

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?

like image 907
user1032752 Avatar asked Aug 13 '26 10:08

user1032752


1 Answers

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.

like image 57
tonypine Avatar answered Aug 16 '26 21:08

tonypine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!