Primitive Type â
TypeBox API is designed around and similar to TypeScript type.
There are a lot of familiar names and behaviors that intersect with TypeScript counter-parts like: String, Number, Boolean, and Object as well as more advanced features like Intersect, KeyOf, Tuple for versatility.
If you are familiar with TypeScript, creating a TypeBox schema has the same behavior as writing a TypeScript type except it provides an actual type validation in runtime.
To create your first schema, import Elysia.t
from Elysia and start with the most basic type:
import { Elysia, t } from 'elysia'
new Elysia()
.get('/', () => 'Hello World!', {
body: t.String()
})
.listen(3000)
import { Elysia, t } from 'elysia'
new Elysia()
.get('/', () => 'Hello World!', {
body: t.String()
})
.listen(3000)
This code tells Elysia to validate an incoming HTTP body, make sure that the body is String, and if it is String, then allow it to flow through the request pipeline and handler.
If the shape doesn't match, then it will throw an error, into Error Life Cycle.
Basic Type â
TypeBox provides a basic primitive type with the same behavior as same as TypeScript type.
The following table lists the most common basic type:
TypeBox | TypeScript |
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
Elysia extends all types from TypeBox allowing you to reference most of the API from TypeBox to use in Elysia.
See TypeBox's Type for additional types that are supported by TypeBox.
Attribute â
TypeBox can accept an argument for more comprehensive behavior based on JSON Schema 7 specification.
TypeBox | TypeScript |
typescript
| |
typescript
| typescript
|
typescript
| typescript
|
typescript
| typescript
|
See JSON Schema 7 specification For more explanation for each attribute.
Honorable Mention â
The following are common patterns that are often found useful when creating a schema.
Union â
Allow multiple types via union.
TypeBox | TypeScript | Value |
typescript
| typescript
|
|
Optional â
Provided in a property of t.Object
, allowing the field to be undefined or optional.
TypeBox | TypeScript | Value |
typescript
| typescript
| typescript
|
Partial â
Allowing all of the fields in t.Object
to be optional.
TypeBox | TypeScript | Value |
typescript
| typescript
| typescript
|
Custom Error â
TypeBox offers an additional "error" property, allowing us to return a custom error message if the field is invalid.
TypeBox | Error |
typescript
|
|
typescript
|
|