Schema for an "Open Union" of string literals #1433
-
|
Hello, I have a field that can be one of multiple strings, or any string. I want to set it up like this so I can provide Typescript-level suggestions for the most common values, but also allow anything. In Typescript, that can be achieved by adding type UnionWithSuggestions = 'a' | 'b' | 'c' | 'd' | (string & {});I tried implementing the same using schemas, and the Typescript portion works as expected, but it causes a schema validation failure: import {Type, Static} from '@sinclair/typebox';
import {TypeCompiler} from '@sinclair/typebox/compiler';
const UnionSchema = Type.Union([
Type.Intersect([Type.String(), Type.Object({})]),
Type.Literal('a'),
Type.Literal('b'),
Type.Literal('c'),
Type.Literal('d'),
]);
type UnionSchemaType = Static<typeof UnionSchema>;
const union: UnionSchemaType = 'something else'; // No TS error, as expected
// But
const compiled = TypeCompiler.Compile(UnionSchema);
const validated = compiled.Check('something else');
console.log(validated); // false - Validation failedIs it possible to achieve something similar that will allow for string suggestions while allowing all strings, and pass both TS and schema validation? Thank you |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
@carcigenicate Hi,
Probably the easiest way to achieve this is to use the Unsafe type to override type inference. Docs: https://sinclairzx81.github.io/typebox/#/docs/type/unsafe Ref: Example import Type, { type Static } from 'typebox'
// this type will validate for all strings, but infer with the ... | (string & {})
const T = Type.Unsafe<'a' | 'b' | 'c' | 'd' | (string & {})>(Type.String())
type T = Static<typeof T>This type will validate for all strings, but will auto complete for the known variants (and allow additional via Hope this helps |
Beta Was this translation helpful? Give feedback.
@carcigenicate Hi,
Probably the easiest way to achieve this is to use the Unsafe type to override type inference.
Docs: https://sinclairzx81.github.io/typebox/#/docs/type/unsafe
Ref: Example
This type will validate for all strings, but will auto complete for the known variants (and allow additional via
(string &…