hapijs / joi

The most powerful data validation library for JS
Other
20.95k stars 1.51k forks source link

fix value type on validation result #3022

Open mastery-benjamin-palko opened 8 months ago

mastery-benjamin-palko commented 8 months ago

The value property returned from .validate is always any, which forces casting to the expected type.

The value should always be known (TSchema) and the error property will be optional, check if error is falsey to determine if value has been properly validated.

Example:


const { value, error } = <schema>.validate(<obj>);

if (error) {
  console.error(error);
  return;
}

// do stuff...

Related to #2677

Marsup commented 8 months ago

The previous type was valid, if you have an error, you can have anything as a value.

mastery-benjamin-palko commented 8 months ago

The previous type was valid, if you have an error, you can have anything as a value.

The issue is that value is always cast as an any, there is no situation where checking for error would return value to its TSchema type.

For example...

const result = <schema>.validate(<obj>);
// result.value is _any_
if (result.error === undefined) {
  // result.value is still _any_
}

Ideally, checking for error being undefined should return value to its proper type.

From VS Code... image

Marsup commented 8 months ago

I think your schema is not typed, maybe you thought that joi auto-inferred the type but that's not currently the case, hopefully soon.

mastery-benjamin-palko commented 8 months ago

I think your schema is not typed, maybe you thought that joi auto-inferred the type but that's not currently the case, hopefully soon.

My schema is typed.

image

Marsup commented 8 months ago

Can you provide a reproduction? I'm not getting what you have https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKQsOAzKERwOQCtnYDcAUMQMYQB2AzvNWQBYCmIAhnALyLIB0EARriZkYAHgBKw6ABNRtKMEoBzADRxWlAJ4A+bQAoAlCXJVacKE2oBXADbwu9Zmx4A3VjeDTWMJnoDeAL5GpMCocHoW1nY8TFAYUJwcXFaU0kyoikzSBnB+xHAF5pa2MK7uVkzEAUA