I'm trying to use Yup to define a schema and generate a Typescript Type that I can use for my objects.
Using InferType seems to work fine for strings and objects, but there's unexpected behavior for arrays. When required()
or defined()
is used with of()
, the types stop working as I would expect.
NOTE: the validation functionality is working fine; I'm only having trouble with InferType
Ideal: InferType combines all operations to the expected type string[]
const schema = yup.array().required().of(yup.string().required());
type SchemaType = yup.InferType<typeof schema>;
// Type should be `string[]`
const schemaInstance: SchemaType = ["string1"];
Actual Scenario 1: array is 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;
Actual Scenario 2: array is 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 = {};
Is there a way to make these types work as expected for an array of strings?
question from:
https://stackoverflow.com/questions/65853623/yup-infertype-for-array-of-strings-not-working-as-expected 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…