Functions in TypeScript
Function Overloads
Master TypeScript function overloading: overload signatures vs implementation signature, typing multiple parameter combinations, and overload ordering rules.
In JavaScript, functions can accept different numbers and types of arguments and return different types accordingly. In TypeScript, Function Overloads allow you to define multiple type signatures for a single function name, providing accurate Intellisense and static checking for all valid calling combinations.
1. Structure of Function Overloads
Function overloading consists of two parts:
1. Overload Signatures: One or more function signatures without a body defining supported argument and return types. 2. Implementation Signature: A final function signature with a body that contains union types flexible enough to handle all overload signatures.
2. Basic Function Overload Example
Note: The Implementation Signature is NOT visible to callers! Callers can only invoke signatures defined in the Overload Signatures.
3. Overloading with Different Return Types
Overloading is essential when the return type depends directly on the input argument type:
4. Ordering Overload Signatures
TypeScript evaluates overload signatures in top-to-bottom order. Always place more specific overload signatures above more general overload signatures.
5. Interactive Code Playground
Test function overloads below:
6. Common Pitfalls & Edge Cases
7. Summary Table
| Concept | Overload Signatures | Implementation Signature |
|---|---|---|
| Has Code Body? | No | Yes |
| Visible to Callers? | Yes | No |
| Quantity Allowed | 1 or more | Exactly 1 |