Add typescript types to Joi.attempt
Support plan
- is this issue currently blocking your project? (yes/no): no
- is this issue affecting a production system? (yes/no): no
Context
- node version: v14.15.3
- module version: v17.4.1
- environment (e.g. node, browser, native): node
- used with (e.g. hapi application, another framework, standalone, ...): koa
- any other relevant information:
What problem are you trying to solve?
Using types when constructing schemas is very useful, for example:
interface User {
name: string;
age: number;
}
const userSchema = Joi.object<User, true>({
name: Joi.string(),
age: Joi.number(),
});
The problem arrises when I use this schema to validate an object with Joi.attempt (I prefer it over validate or validateAsync because it's easier to test and throws errors) the resulting object is of the any type which requires type casting later on. The example above would require the following:
const validatedObj = Joi.attempt(objToValidate, userSchema) as User;
The as User at the end is what bothers me. If not included validatedObj ends up with the any type. Since I initially specified the schema type as User I would expect the result to be of the User type too.
Do you have a new or modified API suggestion to solve the problem?
By changing the definition for attempt in index.d.ts we could automatically set the result type to the type of the schema.
Before:
attempt(value: any, schema: Schema, options?: ValidationOptions): any;
attempt(value: any, schema: Schema, message: string | Error, options?: ValidationOptions): any;
After:
attempt<T = any>(value: any, schema: Schema<T>, options?: ValidationOptions): T;
attempt<T = any>(value: any, schema: Schema<T>, message: string | Error, options?: ValidationOptions): T;
This way, when an ObjectSchema<T> is passed in the schema parameter the result will have its respective type and when any other schema is passed (say ArraySchema or StringSchema) the result type will default to any which is the current behavior.
If this is sounds ok I could make a PR to implement the change.
@cpotdevin This sounds good to me - are you going to raise the PR?
(I'm not a maintainer here, just keen for the TypeScript definitions to work well :))
Hi, this sounds promising. Any news concerning this issue?
would love this