Files
typebox/docs/usage.md

1.8 KiB

Usage

The following shows general usage.

import { Type, type Static } from "@alkdev/typebox";

//--------------------------------------------------------------------------------------------
//
// Let's say you have the following type ...
//
//--------------------------------------------------------------------------------------------

type T = {
  id: string;
  name: string;
  timestamp: number;
};

//--------------------------------------------------------------------------------------------
//
// ... you can express this type in the following way.
//
//--------------------------------------------------------------------------------------------

const T = Type.Object({
  // const T = {
  id: Type.String(), //   type: 'object',
  name: Type.String(), //   properties: {
  timestamp: Type.Integer(), //     id: {
}); //       type: 'string'
//     },
//     name: {
//       type: 'string'
//     },
//     timestamp: {
//       type: 'integer'
//     }
//   },
//   required: [
//     'id',
//     'name',
//     'timestamp'
//   ]
// }

//--------------------------------------------------------------------------------------------
//
// ... then infer back to the original static type this way.
//
//--------------------------------------------------------------------------------------------

type T = Static<typeof T>; // type T = {
//   id: string,
//   name: string,
//   timestamp: number
// }

//--------------------------------------------------------------------------------------------
//
// ... or use the type to parse JavaScript values.
//
//--------------------------------------------------------------------------------------------

import { Value } from "@alkdev/typebox/value";

const R = Value.Parse(T, value); // const R: {
//   id: string,
//   name: string,
//   timestamp: number
// }

Back to Home