@illavv/run_typer - v2.4.1

Typer - Type Checking & Validation Library

Typer is a powerful TypeScript utility library for type checking and validation. It provides a structured and flexible way to verify data types, enforce constraints, and enhance runtime safety in JavaScript and TypeScript applications.

  • Comprehensive Type Checking: Supports checking for primitive types, complex types, and user-defined custom types.
  • Extensible Type System: Register and unregister your own validation functions.
  • Schema-Based Validation: Easily validate object structures.
  • Strict Mode Compatibility: Works seamlessly with TypeScript's strict mode.
  • Asynchronous & Synchronous Support: Ensures correct function return types, even for Promises.

Install Typer via npm:

npm install @illavv/run_typer

import Typer from '@illavv/run_typer';

console.log(Typer.is("Hello", "string")); // true
console.log(Typer.is(123, "number")); // true
console.log(Typer.is(true, "boolean")); // true
console.log(Typer.is([], "array")); // true
console.log(Typer.is({}, "object")); // true

You can define an expected schema and validate an object against it:

const schema = {
name: "string",
age: "number",
address: {
city: "string",
zip: "number"
}
};

const validData = {
name: "John",
age: 30,
address: {
city: "New York",
zip: 10001
}
};

const invalidData = {
name: "John",
age: "thirty",
address: {
city: "New York",
zip: "not-a-number"
}
};

console.log(Typer.checkStructure(schema, validData).isValid); // true
console.log(Typer.checkStructure(schema, invalidData).errors); // Errors in age and zip
Typer.registerType("positive", (value) => {
if (typeof value !== "number" || value <= 0) {
throw new TypeError("Value must be a positive number");
}
return value;
});

console.log(Typer.is(10, "positive")); // true
console.log(Typer.is(-5, "positive")); // false
Typer.unregisterType("positive");
console.log(Typer.listTypes());
const safeFunction = Typer.expect((x: number) => x * 2, {
paramTypes: "number",
returnType: "number"
});

console.log(safeFunction(4)); // 8
console.log(safeFunction("hello")); // Throws TypeError

Checks if a value matches a specified type.

Throws an error if the value does not match any of the specified types.

Registers a custom type.

Removes a registered custom type.

Returns a list of all registered types.

Validates the structure of an object against a defined schema.

Wraps a function and ensures its parameters and return value conform to the expected types.


MIT License


Contributions are welcome! Feel free to submit a pull request or open an issue if you find a bug or have a feature request.


Michael Lavigna


GitHub Repository