tsi*_*ems 10 type-inference typescript yup
我正在尝试使用 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>;
// Type is `any` so the following line compiles
const schemaInstance: SchemaType = {};
Run Code Online (Sandbox Code Playgroud)
有没有办法让这些类型按字符串数组的预期工作?
尝试
const schema = yup.array().of(yup.string().required()).required();
type SchemaType = yup.InferType<typeof schema>;
Run Code Online (Sandbox Code Playgroud)
现在应该可以工作了,您的错误已得到修复。
| 归档时间: |
|
| 查看次数: |
6463 次 |
| 最近记录: |