是的,字符串数组的 InferType 未按预期工作

tsi*_*ems 10 type-inference typescript yup

我正在尝试使用 Yup 定义模式并生成可用于我的对象的 Typescript 类型。

使用 InferType 似乎适用于字符串和对象,但对于数组会出现意外的行为。当required()or 与defined()一起使用时of(),类型将按照我的预期停止工作。

注意:验证功能工作正常;我只是在使用 InferType 时遇到问题

理想: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)

实际场景1:数组是string[] | undefined

const 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)

实际场景2:数组是any

const 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)

有没有办法让这些类型按字符串数组的预期工作?

Lik*_*ple 4

尝试

const schema = yup.array().of(yup.string().required()).required();
type SchemaType = yup.InferType<typeof schema>;
Run Code Online (Sandbox Code Playgroud)

现在应该可以工作了,您的错误已得到修复。