1.3 KiB
1.3 KiB
Home | Installation | Usage | Types | Values | Syntax | TypeRegistry | TypeCheck
Unsafe Types
TypeBox supports user defined types with Unsafe. This type allows you to specify both schema representation and inference type. The following creates an Unsafe type with a number schema that infers as string.
const T = Type.Unsafe<string>({ type: "number" }); // const T = { type: 'number' }
type T = Static<typeof T>; // type T = string - ?
The Unsafe type is often used to create schematics for extended specifications like OpenAPI.
const Nullable = <T extends TSchema>(schema: T) =>
Type.Unsafe<Static<T> | null>({
...schema,
nullable: true,
});
const T = Nullable(Type.String()); // const T = {
// type: 'string',
// nullable: true
// }
type T = Static<typeof T>; // type T = string | null
const StringEnum = <T extends string[]>(values: [...T]) =>
Type.Unsafe<T[number]>({
type: "string",
enum: values,
});
const S = StringEnum(["A", "B", "C"]); // const S = {
// enum: ['A', 'B', 'C']
// }
type S = Static<typeof T>; // type S = 'A' | 'B' | 'C'
Back to Home