Typed Function

4.2.2 · active · verified Sun Apr 19

typed-function (current stable version 4.2.2) is a JavaScript utility library designed to centralize and manage runtime type checking and automatic type conversion for function arguments. It allows developers to define multiple signatures for a single function, supporting union types, the `any` type, and variable arguments. This approach helps in separating type validation logic from core business logic, leading to cleaner code and more informative error messages when functions are called with incorrect input. The library aims to improve robustness and debuggability in JavaScript applications by providing consistent and helpful error messages, preventing silent failures due to invalid inputs. It is actively maintained and supports various environments, including Node.js (>=18) and modern browsers. Its key differentiators include flexible signature definition, detailed error reporting, and optional type conversion.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating basic typed functions with single and multiple signatures, including union types, and handling type mismatch errors.

import typed from 'typed-function';

// Create a typed function with a single signature
const greet = typed({
  'string, string': function (firstName, lastName) {
    return `Hello, ${firstName} ${lastName}!`;
  }
});

console.log(greet('John', 'Doe'));
// Expected output: "Hello, John Doe!"

// Create a typed function with multiple signatures (overloading)
// and a union type for one argument
const calculate = typed({
  'number, number': function (a, b) {
    return a + b;
  },
  'string, string': function (a, b) {
    return a + b; // string concatenation
  },
  'number, number | string': function (a, b) {
    // This signature allows a number and a number or string for the second argument.
    // 'typed-function' will attempt type conversion if possible based on registered types.
    return `Result: ${a + b}`;
  }
});

console.log(calculate(5, 3));
// Expected output: 8
console.log(calculate('Hello', ' World'));
// Expected output: "Hello World"

try {
  console.log(calculate(10, '20')); // Matches 'number, number | string'
} catch (e) {
  console.error("Error calling calculate with number and string:", e.message);
}

// Example of a function designed to throw an error for unsupported types
const processDate = typed({
    'Date': function(date) {
        return `It's a date: ${date.toDateString()}`;
    }
});

try {
    console.log(processDate('not a date'));
} catch (e) {
    console.error("Error calling processDate:", e.message);
}
// Expected: Error calling processDate: TypeError: Unexpected type of argument 1 (expected Date, got string) in function processDate

view raw JSON →