{"id":12217,"library":"typed-function","title":"Typed Function","description":"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.","status":"active","version":"4.2.2","language":"javascript","source_language":"en","source_url":"https://github.com/josdejong/typed-function","tags":["javascript","typed","function","arguments","compose","types"],"install":[{"cmd":"npm install typed-function","lang":"bash","label":"npm"},{"cmd":"yarn add typed-function","lang":"bash","label":"yarn"},{"cmd":"pnpm add typed-function","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The 'typed-function' library exports its main factory function as a default export.","wrong":"import { typed } from 'typed-function'","symbol":"typed","correct":"import typed from 'typed-function'"},{"note":"CommonJS import for Node.js environments. The 'typed' function is the default export.","symbol":"typed","correct":"const typed = require('typed-function')"},{"note":"The 'addType' method is available on the imported 'typed' function itself, not as a separate named export, for extending the type system.","symbol":"addType","correct":"typed.addType({ name: 'MyType', test: (x) => x instanceof MyClass })"}],"quickstart":{"code":"import typed from 'typed-function';\n\n// Create a typed function with a single signature\nconst greet = typed({\n  'string, string': function (firstName, lastName) {\n    return `Hello, ${firstName} ${lastName}!`;\n  }\n});\n\nconsole.log(greet('John', 'Doe'));\n// Expected output: \"Hello, John Doe!\"\n\n// Create a typed function with multiple signatures (overloading)\n// and a union type for one argument\nconst calculate = typed({\n  'number, number': function (a, b) {\n    return a + b;\n  },\n  'string, string': function (a, b) {\n    return a + b; // string concatenation\n  },\n  'number, number | string': function (a, b) {\n    // This signature allows a number and a number or string for the second argument.\n    // 'typed-function' will attempt type conversion if possible based on registered types.\n    return `Result: ${a + b}`;\n  }\n});\n\nconsole.log(calculate(5, 3));\n// Expected output: 8\nconsole.log(calculate('Hello', ' World'));\n// Expected output: \"Hello World\"\n\ntry {\n  console.log(calculate(10, '20')); // Matches 'number, number | string'\n} catch (e) {\n  console.error(\"Error calling calculate with number and string:\", e.message);\n}\n\n// Example of a function designed to throw an error for unsupported types\nconst processDate = typed({\n    'Date': function(date) {\n        return `It's a date: ${date.toDateString()}`;\n    }\n});\n\ntry {\n    console.log(processDate('not a date'));\n} catch (e) {\n    console.error(\"Error calling processDate:\", e.message);\n}\n// Expected: Error calling processDate: TypeError: Unexpected type of argument 1 (expected Date, got string) in function processDate","lang":"javascript","description":"Demonstrates creating basic typed functions with single and multiple signatures, including union types, and handling type mismatch errors."},"warnings":[{"fix":"Apply `typed-function` selectively to public API functions or where robust input validation is critical, avoiding overuse in performance-sensitive internal logic. Profile your application to identify bottlenecks.","message":"Runtime type checking inherently adds a performance overhead. While `typed-function` is optimized, applying it to every function call, especially in hot code paths, can impact performance.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Balance strict type checking with the robustness principle. Only apply stringent type validation where necessary for correctness, API stability, or preventing specific classes of bugs, allowing more flexibility in internal utility functions.","message":"`typed-function` enforces strict input types, but over-applying this strictness can inadvertently reduce a function's flexibility, potentially violating Postel's law ('be liberal in what you accept and conservative in what you send').","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always consult the official release notes and migration guides when upgrading to a new major version to understand specific breaking changes and necessary code adjustments. Test thoroughly after upgrading.","message":"Major version updates (e.g., v3 to v4) can introduce breaking changes to the type signature syntax, `addType` API, or default type conversion behaviors.","severity":"breaking","affected_versions":">=4.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure the arguments provided to the typed function strictly match one of its defined signatures. If type conversion is desired, ensure the necessary types and conversion rules are registered via `typed.addType`.","cause":"A function was called with an argument whose type does not match any of the defined signatures for that argument, and no automatic conversion was possible.","error":"TypeError: Unexpected type of argument X (expected Y, got Z) in function functionName"},{"fix":"Review the function's defined signatures and adjust the call to match an existing signature. Alternatively, add a new signature to the typed function that accommodates the intended argument types and count.","cause":"The arguments provided to the typed function do not match the number or types of any of the defined function signatures.","error":"TypeError: No matching signature found for function functionName with arguments (type1, type2, ..., typeN)"}],"ecosystem":"npm"}