網站搜尋

Yup 條件驗證和 TypeScript


給定以下介面和對應的 Yup 架構。是否有辦法讓 TypeScript 自動推斷條件函數的參數(例如 enabled 和 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 的適當類型是什麼?

答案#1

對我有效的方法是這樣的:

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 與第一個參數和 schema 屬性一起工作,但可惜不能自動完成。

答案#2

你可以試試這樣的東西嗎

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