mrjono1 / joi-to-typescript

Convert Joi Schemas to TypeScript interfaces
MIT License
126 stars 40 forks source link

Conversion not respecting Joi sparse array and including undefined in type #324

Closed ludu12 closed 1 year ago

ludu12 commented 1 year ago

Describe the bug When defining an array schema, the sparse schema method does not produce the correct type. We cannot get undefined to be a valid type within an array.

To Reproduce Steps to reproduce the behavior:

import Joi from 'joi';
import {convertSchema} from 'joi-to-typescript';

const mySchema = Joi.array().items(Joi.string().allow(null, '')).sparse().meta({className: 'MySchema'})

// Passes validation
// { value: [ '', 'string', null, undefined ] }
const validation = mySchema.validate(['', 'string', null, undefined])
console.log(validation)

// Does not have the correct type
// export type MySchema = (string | null | '')[];
const result = convertSchema({}, mySchema)
console.log(result?.content)

Expected behavior

export type MySchema = (string | null | '' | undefined)[];

Actual behavior

export type MySchema = (string | null | '')[];

Additional context Perhaps there is a different way to achieve what we're trying to get.

mrjono1 commented 1 year ago

I'm not at my computer at the moment, can you try adding .optional()? it may help

const mySchema = Joi.array().items(Joi.string().allow(null, '').optional()).sparse().meta({className: 'MySchema'})
mrjono1 commented 1 year ago

does it work without .sparse()? I haven't used that before

ludu12 commented 1 year ago

I'm not at my computer at the moment, can you try adding .optional()? it may help

const mySchema = Joi.array().items(Joi.string().allow(null, '').optional()).sparse().meta({className: 'MySchema'})

so .optional() does not work either:

const mySchema = Joi.array().items(Joi.string().allow(null, '').optional()).sparse().meta({className: 'MySchema'})
const result = convertSchema({}, mySchema)

// export type MySchema = (string | null | '')[];
console.log(result?.content)

If I don't include .sparse() then the following array:

const validation = mySchema.validate(['', 'string', null, undefined])

will fail

mrjono1 commented 1 year ago

I'll need to look into what Joi.describe() produces for this. I'm suspecting it may have a bug???