【问题标题】:Yup conditional validation and TypeScript是的,条件验证和 TypeScript
【发布时间】:2021-06-24 23:53:24
【问题描述】:

给定以下接口和相应的Yup 架构。 TypeScript 有没有办法自动推断条件函数参数(例如 enabledschema)?

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 的合适类型是什么?

【问题讨论】:

标签: typescript yup


【解决方案1】:

你能试试这样的吗

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

【讨论】:

    【解决方案2】:

    对我有用的是这样的:

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

    我设法让 typescript 与第一个参数和模式属性一起工作,但遗憾的是,它并没有自动运行。

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多