Skip to content
Advertisement

Typescript – Type a function that accepts an array, alters one of its properties, but still returns the same typed array

I have form fields represented as objects that get mapped over and based upon the type returns React elements:

JavaScript

The problem I’m running into is I’m trying to validate the fields after a form is submitted and check for any errors in value:

JavaScript

but this reusable validate function has a ts error:

JavaScript

Since validatedFields turns into:

JavaScript

and it’s returned { validatedFields, errors }, it throws this TS error:

JavaScript

Is there a way to infer T as an array of objects that expects at least 4 (or more) properties, but returns the same typed array (just with an updated errors property)?

Typescript Playground

Advertisement

Answer

I managed to figure it out by extending T to any[] and then defining the result of validatedFields as T to preserve the passed in types:

JavaScript

Typescript playground

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement