What is function overloading in general?
Function overloading or method overloading is the ability to create multiple functions of the same name with different implementations (Wikipedia)
What is function overloading in JS?
This feature is not possible in JS - the last defined function is taken in case of multiple declarations:
function foo(a1, a2) { return `${a1}, ${a2}` }
function foo(a1) { return `${a1}` } // replaces above `foo` declaration
foo(42, "foo") // "42"
... and in TS?
Overloads are a compile-time construct with no impact on the JS runtime:
function foo(s: string): string // overload #1 of foo
function foo(s: string, n: number): number // overload #2 of foo
function foo(s: string, n?: number): string | number {/* ... */} // foo implementation
A duplicate implementation error is triggered, if you use above code (safer than JS). TS chooses the first fitting overload in top-down order, so overloads are sorted from most specific to most broad.
Method overloading in TS: a more complex example
Overloaded class method types can be used in a similar way to function overloading:
class LayerFactory {
createFeatureLayer(a1: string, a2: number): string
createFeatureLayer(a1: number, a2: boolean, a3: string): number
createFeatureLayer(a1: string | number, a2: number | boolean, a3?: string)
: number | string { /*... your implementation*/ }
}
const fact = new LayerFactory()
fact.createFeatureLayer("foo", 42) // string
fact.createFeatureLayer(3, true, "bar") // number
The vastly different overloads are possible, as the function implementation is compatible to all overload signatures - enforced by the compiler.
More infos: