How to use the runtypes.match function in runtypes

To help you get started, we’ve selected a few runtypes examples, based on popular ways it is used in public projects.

github pelotom / runtypes / examples / src / union-values.ts View on Github external
Literal('Thursday'),
  Literal('Friday'),
  Literal('Saturday'),
);

// Extract the static type
type Day = Static<typeof Day>; // = 'Sunday' | 'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday' | 'Saturday'

// Extract enumerated literal values
const days: Day[] = Day.alternatives.map(lit => lit.value);

for (const day of days) {
  console.log(`Good morning, it's ${day}!`);
}

const isWeekend = match(
  [Literal('Sunday'), () => true],
  [Literal('Saturday'), () => true],
  [Day, () => false],
);
github pelotom / runtypes / examples / src / shapes.ts View on Github external
import { match, Record, Number, Union, Static } from 'runtypes';

const Square = Record({ size: Number });
const Rectangle = Record({ width: Number, height: Number });
const Circle = Record({ radius: Number });

const Shape = Union(Square, Rectangle, Circle);

const area = Shape.match(
  ({ size }) => Math.pow(size, 2),
  ({ width, height }) => width * height,
  ({ radius }) => Math.PI * Math.pow(radius, 2),
);

const hasCorners = match(
  [Circle, () => false],
  [Union(Square, Rectangle), () => true]
);