joi
joi copied to clipboard
Type definition related question
Support plan
- is this issue currently blocking your project? (yes/no): no
- is this issue affecting a production system? (yes/no): yes
Context
- node version: v18.5.0
- module version: 17.6.0
- environment (e.g. node, browser, native): node
- used with (e.g. hapi application, another framework, standalone, ...): NestJS
- any other relevant information: typescript and extend() topic
How can we help?
I'm wondering if and how should I correctly "type" the following code
config.custom-schemas.ts
const xExtension = {
type: 'x',
base: Joi.object().keys({
a: Joi.string().required(),
b: Joi.number().strict().required(),
c: Joi.number().min(0).max(1).required(),
}),
coerce: {
from: 'string',
method(value: string) {
if (value[0] !== '{' && !/^\s*\{/.test(value)) {
return;
}
try {
return { value: Bourne.parse(value) };
} catch (ignoreErr) {}
},
},
};
export default Joi.extend(xExtension) as typeof Joi & {
x(): Joi.AnySchema<?>;
};
As you can see I'm taking the advantage of the base in order to fully create the schema and coercing it from a string.
What would be the generic to be passed to the Joi.AnySchema<?> type? Should I be using directly the Joi.ObjectSchema instead?
Thank you in advance!
That would make sense to me, as your extension is an object. if your base was an array schema, you'd want to indicate that your extension is also an array schema.
I would type it as x<T extends { a: string; b: number; c: number }>(): Joi.ObjectSchema<T>. You could also put a default on T with the same content as the extends.