How to use the runtypes.String.withConstraint 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.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Hypercubed / dynamo / tests / types-runtypes.spec.ts View on Github external
import { assert, IsExact } from 'conditional-type-checks';

interface ConstraintToken<V> extends Constraint<any> {
  name: string;
  new(...args: any[]): V;
}

function convertConstraint<T extends Runtype<unknown>>(constraint: T, name?: string): ConstraintToken<Static<T>> {
  constraint['name'] = name ? `${name} ${constraint['tag']}` : constraint['tag'];
  guard()(constraint, 'guard');
  return constraint as any;
}

const dynamo = new Dynamo();

const nameConstraint = StringType.withConstraint(x => {
  return x.length > 0;
});

// tslint:disable-next-line:variable-name
const Name = convertConstraint(nameConstraint);
type Name = InstanceType<typeof Name>;

const ageConstraint = NumberType.withConstraint(n => {
  return Number.isInteger(n) && n >= 0;
});

// tslint:disable-next-line:variable-name
const Age = convertConstraint(ageConstraint);
type Age = InstanceType<typeof Age>;

const personRecord = Record({