TCMiranda / joi-extract-type

Provides native type extraction from Joi schemas for Typescript
MIT License
151 stars 27 forks source link

Correctly infer literal from enum #47

Open rubengmurray opened 2 years ago

rubengmurray commented 2 years ago

It would be great to see support of enum values through to extracted types.

I've just tested out the following code with the @latest tag of @hapi/joi & joi-extract-type and it appears they aren't carried through.

Are there any plans to support? Has it been looked at before?

import * as joi from '@hapi/joi';
import 'joi-extract-type';

enum Options {
  OPTION_ONE = 1,
  OPTION_TWO = 2,
  OPTION_THREE = 3
};

const optionArgs = joi.object({
  option: joi.number().valid(...Object.values(Options).filter(o => typeof o === 'number'))
})

type OptionSchema = joi.extractType<typeof optionArgs>

// passes (expect to pass)
const myObjOne: OptionSchema = {
  option: 1
};

// passes (expect to fail)
const myObjTwo: OptionSchema = {
  option: 9
};

// fails (expect to fail)
const myObjThree: OptionSchema = {
  option: 'help'
};

Versions

  "dependencies": {
    "@hapi/joi": "17.1.1",
    "joi-extract-type": "15.0.8"
  }
rubengmurray commented 2 years ago

Just occurred to me this is not necessarily enum specific and is more of a support of the valid() method...

Looks like it's mentioned here a while back 👀

https://github.com/TCMiranda/joi-extract-type/issues/5#issue-372240680