Amy Blankenship
Mar 11, 2024

--

A lot of times you can massage things to have the same input and output types with a little thought.

But assuming you can't...

createStringPropLengthValidator('name', 2, NaN, 'Name must be at least 2 characters')

createNumberPropValidator('age', 0, NaN, 'Age cannot be less than 0')

etc.

The real project I created the date validation for had different return types for different errors. For example, having one date be null was a recoverable error, so the return came back with 2 date objects that would fix the problem without bothering the user. I didn't provide that as an example because your example just had strings. The calling code used type guards to figure out what to do based on the type of the return.

--

--

Amy Blankenship
Amy Blankenship

Written by Amy Blankenship

Full Stack developer at fintech company. I mainly write about React, Javascript, Typescript, and testing.

Responses (1)