typescript - 是的,条件验证和 TypeScript
问题描述
给定以下接口和相应的Yup
架构。TypeScript 有没有办法自动推断条件函数参数(例如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)
})
我试过了yupObject()<Foo>
,shape<Foo>(..)
但都没有帮助。如果不能自动完成,schema
在这种情况下适合的类型是什么?
解决方案
你能试试这样的吗
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()
}
推荐阅读
- python - 如何在所有其他请求中使用在第一个请求中创建的 sklearn pickle 对象
- apache-kafka - 如何将 *windowed* KTable 实体化为 Kafka 主题
- c++ - 如何正确清理对象指针向量中的元素
- youtube - 如何对 YouTube 提要进行分页
- swift - 如何从 iOS swift 中的 alamofire/swiftyJson 字典到 JSON 字符串和 JSON 字符串到字典
- php - 聚合中的组,包括 mongodb 中的空值
- decode - 如何解码 Skype for Business 服务返回的访问令牌
- jmeter - 使用 jmeter 从响应中提取十六进制编码值
- redux - Redux Thunk Async React 组件是否挂载
- tensorflow - 在 Tensorflow 中运行 LSTM 时出现 ResourceExhausted 错误或 OOM