Introducing @autometa/overloaded: A Library for Simplifying Function and Method Overloads
@autometa/overloaded is a small library that simplifies the creation of function and method overloads. It uses a zod-inspired syntax and ensures that full typings are accurately carried across your overload implementations. It also throws meaningful errors when your arguments don't match an overload, if no fallback is provided.
To add @autometa/overloaded to your node project via NPM, simply run:
npm add @autometa/overloaded
Here's an example of a function with two overloads:
- Accept two strings, returning the combined string with a newline between
- Accept two numbers, returning the sum of the inputs
Without using @autometa/overloaded, the solution would look like this:
function add(a: string, b: string): string;
function add(a: number, b: number): number;
function add(a: string | number, b: string | number): string | number {
if (typeof a === "string") {
if (typeof b === "string") {
return a + "\n" + b;
}
} else if (typeof a === "number") {
if (typeof b === "number") {
return a + b;
}
}
}
Using @autometa/overloaded, the same function can be written like this:
import { overload } from "@autometa/overloaded";
const add = overload({
(a: string, b: string) => a + "\n" + b,
(a: number, b: number) => a + b,
});
@autometa/overloaded is not yet released as version 1.0.0, so it may contain bugs or be subject to contract changes. However, it should be mostly stable. For more information and full documentation, visit the NPM link: https://www.npmjs.com/package/@autometa/overloaded