Files
typebox/docs/types/conditional.md

1.4 KiB

Home | Installation | Usage | Types | Values | Syntax | TypeRegistry | TypeCheck

Conditional Types

TypeBox supports runtime conditional types with the Extends function. This function performs a structural assignability check against the first (left) and second (right) arguments and will return either the third (true) or fourth (false) argument based on the result. The conditional types Exclude and Extract are also supported. The following shows both TypeScript and TypeBox examples of conditional types.

// Extends
const A = Type.Extends(
  // type A = string extends number ? 1 : 2
  Type.String(), //
  Type.Number(), // ... evaluated as
  Type.Literal(1), //
  Type.Literal(2) // const A: TLiteral<2>
);

// Extract
const B = Type.Extract(
  // type B = Extract<1 | 2 | 3, 1>
  Type.Union([
    //
    Type.Literal(1), // ... evaluated as
    Type.Literal(2), //
    Type.Literal(3), // const B: TLiteral<1>
  ]),
  Type.Literal(1)
);

// Exclude
const C = Type.Exclude(
  // type C = Exclude<1 | 2 | 3, 1>
  Type.Union([
    //
    Type.Literal(1), // ... evaluated as
    Type.Literal(2), //
    Type.Literal(3), // const C: TUnion<[
  ]), //   TLiteral<2>,
  Type.Literal(1) //   TLiteral<3>,
); // ]>

Back to Home