or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-rtts-assert

A runtime type assertion library for Traceur-compiled JavaScript applications.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/rtts-assert@0.0.x

To install, run

npx @tessl/cli install tessl/npm-rtts-assert@0.0.0

index.mddocs/

rtts_assert

rtts_assert is a runtime type assertion library designed for Traceur-compiled JavaScript applications. It provides comprehensive type checking and validation capabilities for both primitive and complex types, including custom type definitions and integration with Traceur's type annotation system.

Package Information

  • Package Name: rtts-assert
  • Package Type: npm
  • Language: JavaScript (ES6) with Traceur
  • Installation: npm install rtts-assert

Core Imports

import { assert } from "rtts-assert";

For CommonJS:

const { assert } = require("rtts-assert");

Basic Usage

import { assert } from "rtts-assert";

// Basic type checking with primitive values
assert.type("hello", assert.string);
assert.type(42, assert.number);
assert.type(true, assert.boolean);

// Custom class type checking  
class User {}
const user = new User();
assert.type(user, User);

// Fluent API for type validation
assert("hello").is(assert.string);
assert(42).is(assert.string, assert.number); // Multiple type options (OR logic)

// Complex type validation
const UserType = assert.define('User', function(value) {
  assert(value).is(assert.structure({
    name: assert.string,
    age: assert.number
  }));
});

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 }
];

assert.type(users, assert.arrayOf(UserType));

Architecture

rtts_assert is built around several core concepts:

  • Type Assertion Engine: Core validation logic using instanceof checks and custom assertion methods
  • Fluent API: assert(value).is(...types) pattern for flexible type checking
  • Custom Type System: assert.define() for creating reusable type definitions with validation logic
  • Traceur Integration: Native support for Traceur type annotations and runtime type checks
  • Error Reporting: Detailed error messages with validation context and nested error structures

Capabilities

Core Type Assertion

Fundamental type checking functions that validate values against expected types.

/**
 * Asserts that a value is of the specified type, throws error if not
 * @param actual - Value to check  
 * @param T - Type constructor or type definition
 * @throws Error with detailed message if type check fails
 */
assert.type(actual, T);

/**
 * Validates function arguments in pairs (value, type, value, type, ...)
 * @param ...params - Alternating values and types  
 * @throws Error with position-specific messages for invalid arguments
 */
assert.argumentTypes(...params);

/**
 * Validates return value type and returns the value if valid
 * @param actual - Return value to validate
 * @param T - Expected return type
 * @returns The validated value
 * @throws Error if return type is invalid
 */
assert.returnType(actual, T);

Fluent Type Validation

Flexible type checking using a fluent API pattern.

/**
 * Creates a fluent validation object for the given value
 * @param value - Value to validate
 * @returns Object with 'is' method for type checking
 */
assert(value);

/**
 * Fluent validation interface
 */
interface FluentValidator {
  /** 
   * Validates value against one or more types (OR logic)
   * @param ...types - Variable number of type constructors
   * @returns true if value matches any type, false otherwise
   */
  is(...types): boolean;
}

Usage Example:

// Single type check
const isValid = assert("hello").is(assert.string);

// Multiple type options (OR logic)
const isValidNumber = assert(42).is(assert.string, assert.number);

// Complex validation in custom types
const MyType = assert.define('MyType', function(value) {
  return assert(value).is(Object);
});

Custom Type Definitions

System for creating reusable type definitions with custom validation logic.

/**
 * Creates custom type definitions with validation logic
 * @param classOrName - Existing class constructor or string name for new interface
 * @param check - Function containing validation logic
 * @returns Type constructor with attached 'assert' method
 */
assert.define(classOrName, check);

/**
 * Adds error message to current validation stack
 * @param message - Error message string
 */
assert.fail(message);

Usage Examples:

// Define interface from string name
const Email = assert.define('Email', function(value) {
  assert(value).is(assert.string);
  if (value.indexOf('@') === -1) {
    assert.fail('must contain "@" symbol');
  }
});

// Add assertion to existing class
class User {}
assert.define(User, function(value) {
  assert(value).is(Function, Object);
});

// Use custom types
assert.type("user@example.com", Email);
assert.type(new User(), User);

Predefined Type Validators

Built-in validators for common primitive types.

/**
 * String type validator using typeof check
 */
assert.string;

/**
 * Number type validator using typeof check
 */
assert.number;

/**
 * Boolean type validator using typeof check
 */
assert.boolean;

Complex Type Constructors

Validators for arrays and structured objects with specific type requirements.

/**
 * Creates validator for arrays containing items of specified types
 * @param ...types - Variable number of type constructors
 * @returns Type constructor for array validation
 */
assert.arrayOf(...types);

/**
 * Creates validator for objects with specific property types
 * @param definition - Object mapping property names to type constructors
 * @returns Type constructor for object structure validation
 */
assert.structure(definition);

Usage Examples:

// Array validation
const StringOrNumberArray = assert.arrayOf(assert.string, assert.number);
assert.type(["hello", 42, "world"], StringOrNumberArray);

// Object structure validation
const UserStructure = assert.structure({
  name: assert.string,
  age: assert.number,
  active: assert.boolean
});
assert.type({ name: "Alice", age: 25, active: true }, UserStructure);

// Nested structure validation
const ContactStructure = assert.structure({
  user: UserStructure,
  emails: assert.arrayOf(assert.string)
});

Integration with Traceur

rtts_assert integrates seamlessly with Traceur's type annotation system for automatic runtime type checking:

// Function with type annotations
function greet(name: string): string {
  return `Hello, ${name}!`;
}

// Variable type annotations
var count: number = 42;
var users: User[] = [];

// Void return type
function logMessage(msg: string): void {
  console.log(msg);
}

When compiled with Traceur using --types=true --type-assertions=true --type-assertion-module="path/to/assert", these annotations automatically generate calls to assert.argumentTypes(), assert.returnType(), and assert.type().

Traceur Primitive Types:

rtts-assert integrates directly with Traceur's runtime type system through $traceurRuntime.type:

  • $traceurRuntime.type.string - String type (checked with typeof value === 'string')
  • $traceurRuntime.type.number - Number type (checked with typeof value === 'number')
  • $traceurRuntime.type.boolean - Boolean type (checked with typeof value === 'boolean')
  • $traceurRuntime.type.void - Void/undefined type (checked with typeof value === 'undefined')
  • $traceurRuntime.type.any - Any type (always passes validation)

These primitive types are used internally by rtts-assert and automatically by Traceur-generated code.

Error Handling

rtts_assert provides detailed error messages with validation context:

// Basic error
assert.type(123, assert.string);
// Error: Expected an instance of string, got 123!

// Nested validation errors
const UserType = assert.define('User', function(value) {
  assert(value).is(assert.structure({
    name: assert.string,
    contact: assert.structure({
      email: assert.string
    })
  }));
});

assert.type({ name: "Alice", contact: { email: 123 } }, UserType);
// Error: Expected an instance of User, got {...}!
//   - {...} is not instance of object with properties name, contact
//     - 123 is not instance of string

// Argument validation errors
function process(data: string, count: number) {
  // Generated by Traceur: assert.argumentTypes(data, assert.string, count, assert.number);
}

process(123, "invalid");
// Error: Invalid arguments given!
//   - 1st argument has to be an instance of string, got 123
//   - 2nd argument has to be an instance of number, got "invalid"

Types

/**
 * Core assert function interface
 */
interface Assert {
  (value: any): FluentValidator;
  type(actual: any, T: any): void;
  argumentTypes(...params: any[]): void;
  returnType(actual: any, T: any): any;
  define(classOrName: any, check: Function): any;
  fail(message: string): void;
  string: TypeValidator;
  number: TypeValidator;
  boolean: TypeValidator;
  arrayOf(...types: any[]): TypeValidator;
  structure(definition: {[key: string]: any}): TypeValidator;
}

/**
 * Fluent validation interface
 */
interface FluentValidator {
  is(...types: any[]): boolean;
}

/**
 * Type validator with assert method
 */
interface TypeValidator {
  assert(value: any): boolean | void;
  __assertName?: string;
}