我正在尝试使用 Yup 定义模式并生成可用于我的对象的 Typescript 类型。
使用 InferType 似乎适用于字符串和对象,但对于数组会出现意外的行为。当required()or 与defined()一起使用时of(),类型将按照我的预期停止工作。
注意:验证功能工作正常;我只是在使用 InferType 时遇到问题
string[]const schema = yup.array().required().of(yup.string().required());
type SchemaType = yup.InferType<typeof schema>;
// Type should be `string[]`
const schemaInstance: SchemaType = ["string1"];
Run Code Online (Sandbox Code Playgroud)
string[] | undefinedconst schema = yup.array().required().of(yup.string().required());
type SchemaType = yup.InferType<typeof schema>;
// Type is `string[] | undefined` so the following line compiles
const schemaInstance: SchemaType = undefined;
Run Code Online (Sandbox Code Playgroud)
anyconst schema = yup.array().of(yup.string().required()).required();
type SchemaType = yup.InferType<typeof schema>; …Run Code Online (Sandbox Code Playgroud)