Comments (4)
@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.
@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.
@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.
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)
- Transform + Map/Index does not work HOT 4
- Update the error message for required properties HOT 3
- Covariance issue with `TypeCheck<TSchema>` and `TypeCheck<TObject<{}>>` HOT 1
- Default values in nested objects are not generated HOT 2
- Doubt on Record HOT 2
- TypeCompiler compile on Type.Strict(T) - Preflight validation check failed to guard for the given schema HOT 2
- Max call stack size exceeded HOT 1
- Value.Convert() doesn't work with nullable record HOT 1
- Variadic Any Typed function parameters HOT 2
- How to do a cross field validation? HOT 3
- Undefined is incorrectly handled in Diff HOT 3
- QoL helper: `TypeCheck.Ensure` HOT 3
- Usage of `Type.Composite` with `Type.TemplateLiteral` HOT 3
- `Type.Omit` mixed with `Type.Union` is not preserving the `additionalProperties` attribute HOT 2
- Advice to compose types HOT 3
- Access to schema properties for non TObject schemas HOT 5
- Type.Optional with Type.Transform unexpected behaviour HOT 1
- ts(7056) when you try to export a big union type HOT 1
- `Value.Default` does not traverse object schema HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from typebox.