farm-plugin-overload
v0.2.1
Published
Compile-time function overloading for FarmFE — @overload decorator groups functions into dispatchers with i18n error messages
Downloads
500
Maintainers
Readme
farm-plugin-overload
Compile-time function overloading for FarmFE — implement runtime overloading via @overload decorator with i18n error messages.
Install
npm install farm-plugin-overloadConcept
JavaScript/TypeScript supports overloading in declarations but not in implementations. This plugin bridges that gap: mark multiple functions with @overload('name') and the compiler generates a single dispatcher that selects the right implementation based on argument count and types.
Usage
import overload from 'farm-plugin-overload'
export default {
plugins: [overload()],
}Example
@overload('greet')
function greet_0(): string { return 'Hello!' }
@overload('greet')
function greet_1(name: string): string { return `Hello, ${name}` }
@overload('greet')
function greet_2(name: string, age: number): string { return `Hello, ${name}, age ${age}` }
// Call the unified name — dispatcher selects the right implementation
greet() // → 'Hello!'
greet('Alice') // → 'Hello, Alice'
greet('Alice', 30) // → 'Hello, Alice, age 30'
greet(true) // → Error: No overload for "greet" matches (boolean)Compiles to:
function greet_0() { return 'Hello!' }
function greet_1(name) { return `Hello, ${name}` }
function greet_2(name, age) { return `Hello, ${name}, age ${age}` }
function greet(...args) {
if (args.length === 0) return greet_0(...args)
if (args.length === 1 && typeof args[0] === "string") return greet_1(...args)
if (args.length === 2 && typeof args[0] === "string" && typeof args[1] === "number") return greet_2(...args)
throw new Error(`No overload for function "greet" matches the provided arguments (${args.map(a => typeof a).join(", ")}).`)
}.d.ts Generation
The plugin generates TypeScript declaration files with proper overload signatures, so IDEs show correct type hints:
declare function greet(): string;
declare function greet(name: string): string;
declare function greet(name: string, age: number): string;i18n Error Messages
Runtime errors support multiple locales:
| Locale | Code | Example |
|--------|------|---------|
| English | en | No overload for function "greet" matches the provided arguments (boolean). |
| 中文 | zh | 函数 "greet" 没有匹配参数 (boolean) 的重载。 |
| Latina | la | Nulla supersonicatio pro functione "greet" congrit argumentis (boolean). |
overload({ locale: 'zh' }) // Chinese error messagesOptions
locale— Error message locale. Default:'en'. Supported:'en','zh','la'extensions— File extensions to process. Default:['.ts', '.tsx', '.js', '.jsx']
License
MIT
