是的 Typescript 并集/交集验证

Shu*_*muu 9 typescript yup

对于我使用yup 的项目,但我在从架构中获取良好的类型时遇到问题...理想情况下,我会得到一个类型,该类型显示当属性具有特定值时,必须定义另一个属性!

我构建了一个快速的Codesandbox来显示问题,但如果您不想切换,我也将其发布在这里......

模式定义如下

const schema = yup.object({
  contactForm: yup
    .mixed<"phone" | "email">()
    .required()
    .oneOf(["email", "phone"]),
  email: yup.string().when("contactForm", {
    is: "email",
    then: (schema) => schema.required().email(),
    otherwise: (schema) => schema.transform(() => undefined)
  }),
  phone: yup.string().when("contactForm", {
    is: "phone",
    then: (schema) => schema.required(),
    otherwise: (schema) => schema.transform(() => undefined)
  })
});
Run Code Online (Sandbox Code Playgroud)

模式类型

type Schema = yup.InferType<typeof schema>;

我得到什么:

type Schema = {
    contactForm: "email" | "phone";
    email: string | undefined;
    phone: string | undefined;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我检查具有 TypeScript 的对象时,contactForm: "email"仍然会抱怨电子邮件可能未定义。对于小对象来说这可能没问题,但我有一些模式,当属性具有特定值时需要定义多个属性,这使得 TypeScript 感觉有点无用......

我想要的是

type Schema = {contactForm: "email"; email: string} | {contactForm: "phone"; phone: string};
Run Code Online (Sandbox Code Playgroud)

Yup 不可能做到这一点吗?如果可能的话,我需要如何定义架构?