Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

typescript - Yup InferType for array of strings not working as expected

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...