Syntax Overview

Main flavor

Validate arguments

validate( arguments, [ "JSDOC-EXPRESSION", "JSDOC-EXPRESSION" ] );  // ok or exception

Validate a single value (e.g. return value)

validate( value, "JSDOC-EXPRESSION" ); // ok or exception

Example

import { validate } from "bycontract";

const PdfOptionsType = {
  scale: "?number"
}

/**
 * Example
 * @param {string} path
 * @param {!number} w
 * @param {!number} h
 * @param {PdfOptionsType} options
 * @param {function=} callback
 */
function pdf( path, w, h, options, callback ) {
  validate( arguments, [
    "string",
    "!number",
    "!number",
    PdfOptionsType,
    "function=" ] );
  //...
  const returnValue = Promise.resolve();
  return validate( returnValue, "Promise" );
}

pdf( "/tmp/test.pdf", 1, 1, { scale: 1 } );

// Test it

pdf( "/tmp/test.pdf", "1", 1, { scale: 1 } ); // ByContractError: Argument #1: expected non-nullable but got string

Template Tag flavor

validateContract`
    {JSDOC-EXPRESSION} ${ var1 }
    {JSDOC-EXPRESSION} ${ var2 }
`;

Example

import { validate, typedef } from "bycontract";

typedef("#PdfOptionsType", {
  scale: "number"
});

function pdf( path, w, h, options, callback ) {
  validateContract`
    {string}          ${ path }
    {!number}         ${ w }
    {!number}         ${ h }
    {#PdfOptionsType} ${ options }
    {function=}       ${ callback }
    `;
}

or you can copy/paste from JSDoc:

function pdf( path, w, h, options, callback ) {
  validateContract`
    @param {string}          ${ path }
    @param {!number}         ${ w }
    @param {!number}         ${ h }
    @param {#PdfOptionsType} ${ options }
    @param {function=}       ${ callback }
    `;
}

Property Decorator flavor

@validateJsdoc`
    @param {JSDOC-EXPRESSION} param1
    @param {JSDOC-EXPRESSION} param2
    @returns {JSDOC-EXPRESSION} 
`;

Example

import { validate, typedef } from "bycontract";

typedef("#PdfOptionsType", {
  scale: "number"
});

class Page {
  @validateJsdoc(`
    @param {string}          path
    @param {!number}         w
    @param {!number}         h
    @param {#PdfOptionsType} options
    @param {function=}       callback
    @returns {Promise}
  `)
  pdf( path, w, h, options, callback ) {
    return Promise.resolve();
  }
}
const page = new Page();
page.pdf( "/tmp/test.pdf", "1", 1, { scale: 1 } ); 
// ByContractError: 
// Method: pdf, parameter w: expected non-nullable but got string

This solution requires legacy decorators proposal support. You can get it with following Babel configuration

{
  presets: [
    [ "@babel/preset-env" ]
  ],
  plugins: [
    [ "@babel/plugin-proposal-decorators", { "legacy": true } ]
  ]
}

Last updated