Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extending Joi with Typescript: Preserving types #2357

Closed
digitalcortex opened this issue Apr 23, 2020 · 3 comments
Closed

Extending Joi with Typescript: Preserving types #2357

digitalcortex opened this issue Apr 23, 2020 · 3 comments
Labels
support Questions, discussions, and general support

Comments

@digitalcortex
Copy link

digitalcortex commented Apr 23, 2020

Support plan

  • Community
  • Is it stopping my project? yes
  • Is it affecting my production? no

Context

  • node version: 13.12.0
  • module version: 17.1.1
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, standalone, ...): feathersjs

How can we help?

I'm trying to write multiple custom extensions for Joi using Typescript. The problem is, Joi.extend() seems to be returning "any" type which totally breaks autocomplete. I tried arranging my extension in the following way:

`import mongoose from 'mongoose'
import Joi from '@hapi/joi';

export function ExtendJoiWithObjectId(root: T) {

interface ExtendedStringSchema {
    objectId(): ExtendedStringSchema;
}

interface ObjectIdJoi {
    string(): ExtendedStringSchema;
}

return root.extend((joi) => {
    return {
        type: 'objectId',
        base: joi.string(),
        messages: {
            'objectId.valid': '"{{#label}}" must be a valid mongo id'
        },
        coerce(value, helpers) {
            return { value };
        },
        validate(value, helpers) {
            if (!mongoose.isValidObjectId(value)) {
                return helpers.error('objectId.valid');
            }
        }
    };
}) as ObjectIdJoi; 

}`

but it makes extensions impossible to combine with each other. Is there any good pattern that would allow me to extend Joi and combine all extensions in a single type definition?

@digitalcortex digitalcortex added the support Questions, discussions, and general support label Apr 23, 2020
@SimonSchick
Copy link

import * as Joi from '@hapi/joi';

interface ObjectIdJoi extends Joi {
    string(): ExtendedStringSchema;
}

joi.extend also takes a vararg.

@abhisekp
Copy link

interface ObjectIdJoi extends BaseJoi.StringSchema {
  objectId(): this;
}

Ref: http://definitelytyped.org/docs/joi--joi/modules/joi.html#string

@ignacioambia
Copy link

Hi! @hueniverse at the end of the day, how did you solve it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
support Questions, discussions, and general support
Projects
None yet
Development

No branches or pull requests

5 participants