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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With