3 ms·
https://www.tutorialsteacher.com/typescript/function-overloading https://www.tutorialsteacher.com/typescript/function-overloa... TS/JS don't allow for overload
by jimbob45 7y ago
https://www.tutorialsteacher.com/typescript/function-overloading https://www.tutorialsteacher.com/typescript/function-overloa...
TS/JS don't allow for overloading the way that other languages do - it does not allow you to differentiate between functions via number of parameters, only types of parameters. If you try to differentiate based on number of parameters, it will simply use whichever definition of that function name it finds first.
- deleted 7y ago[deleted]
- 52-6F-62 7y agoThat's not [entirely] my experience. Here's a quick example: Declaration file style: --- // add.d.ts export declare function add(a: number, b: number): number; export declare function add(a: number, b: number, c: number): number; export declare function add(a: number, b: number, c: number, d: number): number; --- // add.js function add() { switch (arguments.length) { case 2: return arguments[0] + arguments[1]; case 3: return arguments[0] + arguments[1] + arguments[2]; case 4: return arguments[0] + arguments[1] + arguments[2] + arguments[3]; default: throw new Error("Too few or too many arguments. Number of arguments: " + arguments.length); } } module.exports = { add }; --- // adding.ts import { add } from "./add"; console.log("4 + 4 =", add(4,4)); console.log("4 + 4 + 4 =", add(4,4,4)); console.log("4 + 4 + 4 + 4 =", add(4,4,4,4)); --- (Gist: https://gist.github.com/Robert-Fairley/98a2da3f0361e524f4e056d947a6172a https://gist.github.com/Robert-Fairley/98a2da3f0361e524f4e05...) It will default to the first function name, but it definitely allows for overloading the number of parameters. It's not perfect as you do still have to implement the function as it would need to be implemented for JS