Giter VIP home page Giter VIP logo

Comments (4)

sinclairzx81 avatar sinclairzx81 commented on August 20, 2024 1

@dswbx Hi, Apologies for the delay in reply.

I understand that you might have a different focus, since there are many validators around. But would you accept a pull request to add the enum-check on string types? As far as I can say that's a very common use-case, e.g. and the pattern is supported. I could probably add this inside this function (along with a unit test of course).

Unfortunately, I can't accept any updates to the current Enum schematics at this time (mostly to lock down this aspect of the library so I've a basis for updating it). The eventual goal is to reshape Type.Enum into a { enum: [...] }, which requires fairly heavy refactoring of how TB currently handles Union types. The current setup is fairly consistent around anyOf (schematics, inference and validation) so just want to keep things as they are so I can investigate reshaping things from a consistent state (there is a lot of complexity down there)

Thanks for the offer tho, but can only really advise the using the approach shown above for now. Will close off this issue for now.
All the best!
S

from typebox.

sinclairzx81 avatar sinclairzx81 commented on August 20, 2024

@dswbx Hi,

By default, the TypeBox compiler and value checkers will only validate against structures defined by TypeBox (so it only checks a subset of the specification). This may change in later revisions where there is some consideration going towards developing a full standards compliant validator that supports all keywords, but this is a fair way off.

In the interim, you can register custom schematics + inference in the following way.

import { Type, Kind, SchemaOptions, TypeRegistry, Static } from '@sinclair/typebox'
import { Value } from 'src/value/value'

// create a custom type on the type registry 
TypeRegistry.Set('StringEnum', (schema: { enum: string[] }, value: unknown) => {
  return typeof value === 'string' && schema.enum.includes(value)
})

// create a type method for string enum
export function StringEnum<T extends string[]>(values: [...T], options: SchemaOptions = {}) {
  return Type.Unsafe<T[number]>({ ...options, [Kind]: 'StringEnum', enum: values })
}

// use as custom type
const T = StringEnum(['A', 'B', 'C'])   // TUnsafe<'A' | 'B' | 'C'>
type T = Static<typeof T>               // 'A' | 'B' | 'C'

Value.Check(T, 'A') // true
Value.Check(T, 'B') // true
Value.Check(T, 'C') // true
Value.Check(T, 'D') // false

By setting a custom validator on the TypeRegistry, this will allow you use Value.Check and TypeCompiler to check enum values.
Hope this helps
S

from typebox.

dswbx avatar dswbx commented on August 20, 2024

@sinclairzx81 thank you very much, this works nicely! Any chance to modify the error message (so that I can specify that the kind is matched but the value is wrong)?
(EDIT: found it and updated my example. Works great!)

I understand that you might have a different focus, since there are many validators around. But would you accept a pull request to add the enum-check on string types? As far as I can say that's a very common use-case, e.g. and the pattern is supported. I could probably add this inside this function (along with a unit test of course).

from typebox.

dearlordylord avatar dearlordylord commented on August 20, 2024

as a way to overcome it you can do Value.Decode catching the error and narrowing the error type with Value.Errors

try {
    const r = Value.Decode(User, u);
    return { _tag: 'right', value: r };
  } catch (e) {
    // type of their errors is unknown, you should additionally call error list methods
    return { _tag: 'left', error: [...Value.Errors(User, u)] };
  }

from typebox.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.