oneOf functionality? #1423
-
|
First of all, thanks for putting this tool together, it looks like it'll simplify what I'm trying to do greatly. I've looked through the documentation, and found types that convert to JSON Schema's anyOf and allOf keywords, but so far I have not been able to find a type that converts to the oneOf keyword. Has such a thing been implemented? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
@free-mana Hi,
TypeBox doesn't provide a Type.* function to create import Type from 'typebox'
// ------------------------------------------------------------------
// UnionExclusiveOr
// ------------------------------------------------------------------
export interface TUnionExclusiveOr<Types extends Type.TSchema[]> extends Type.TSchema {
oneOf: Types
}
export function UnionExclusiveOr<Types extends Type.TSchema[]>(types: [...Types]): TUnionExclusiveOr<Types> {
return { oneOf: types }
}
// ------------------------------------------------------------------
// Usage
// ------------------------------------------------------------------
const T = UnionExclusiveOr([
Type.Number(),
Type.String(),
])
type T = Type.Static<typeof T> // type T = string | numberThe TUnionExclusiveOr will infer correctly (via Static) and can also be passed to TypeBox validators (as TypeBox's validation is based on JSON Schema). However compositional support (i.e applying utility types such as Extract/Exclude) are limited to Union only. Hope this helps! |
Beta Was this translation helpful? Give feedback.
@free-mana Hi,
TypeBox doesn't provide a Type.* function to create
oneOfschematics by default because TypeScript has no concept of XOR. TypeScript only supports OR (Union) and AND (Intersect) logical type expressions. This said, it is still technically possible to createoneOfschematics in the following way...TypeScript Link Here