首页 > 解决方案 > 是的,条件验证和 TypeScript

问题描述

给定以下接口和相应的Yup架构。TypeScript 有没有办法自动推断条件函数参数(例如enabledand 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)
})

我试过了yupObject()<Foo>shape<Foo>(..)但都没有帮助。如果不能自动完成,schema在这种情况下适合的类型是什么?

标签: typescriptyup

解决方案


你能试试这样的吗

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() 
}

推荐阅读