Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
Solidity Function Overloading
Next article icon

TypeScript Function Overloads

Last Updated : 23 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript function overloads enable defining multiple signatures for a single function, allowing it to handle various parameter types or counts.

  • Enhances type safety by ensuring correct argument handling.
  • Improves code flexibility and readability.
JavaScript
function greet(person: string): string; function greet(person: string, age: number): string; function greet(person: string, age?: number): string {     if (age !== undefined) {         return `Hello, ${person}! You are ${age} years old.`;     }     return `Hello, ${person}!`; }  console.log(greet("Alice"));  console.log(greet("Bob", 30)); 
  • The function greet has two overloads: one with a single parameter person and another with person and age.
  • The implementation checks if age is provided and returns an appropriate greeting.

Output:

Hello, Alice!
Hello, Bob! You are 30 years old.

More Example of TypeScript function Overloads

Adding Numbers or Concatenating Strings

JavaScript
function combine(a: number, b: number): number; function combine(a: string, b: string): string; function combine(a: any, b: any): any {     return a + b; }  console.log(combine(5, 10));        console.log(combine("Hello, ", "World!")); 
  • The combine function is overloaded to handle both numbers and strings, either adding or concatenating them.
  • The implementation uses a single function to manage both scenarios.

Output:

15
Hello, World!

Fetching Data by ID or Query

JavaScript
function fetchData(id: number): string; function fetchData(query: string): string[]; function fetchData(param: any): any {     if (typeof param === 'number') {         return `Data for ID: ${param}`;     } else {         return [`Result for query: ${param}`];     } }  console.log(fetchData(42));             console.log(fetchData("search term")); 
  • The fetchData function is overloaded to accept either a numeric ID or a string query.
  • It returns a string for an ID and an array of strings for a query.

Output:

Data for ID: 42
Result for query: search term

Calculating Area for Different Shapes

JavaScript
function calculateArea(radius: number): number; function calculateArea(length: number, width: number): number; function calculateArea(...args: number[]): number {     if (args.length === 1) {         return Math.PI * args[0] ** 2;     } else {         return args[0] * args[1];     } }  console.log(calculateArea(5));          console.log(calculateArea(10, 20));     
  • The calculateArea function is overloaded to compute the area of a circle when given one argument and a rectangle when given two arguments.
  • It uses rest parameters to handle a varying number of arguments.

Output:

78.53981633974483
200

Best Practices for Using TypeScript Function Overloads

  • Define Clear and Specific Overloads: Ensure each overload signature is precise and unambiguous to enhance code readability and maintainability.
  • Order Overloads from Most Specific to Least Specific: Arrange overloads so that more specific signatures appear before more general ones, aiding the TypeScript compiler in selecting the correct overload.
  • Implement a Generalized Function Body: The function implementation should accommodate all defined overloads, using type guards or conditional logic to handle different parameter types appropriately.

Next Article
Solidity Function Overloading

A

akshitsaxenaa09
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks Premier League 2023

Similar Reads

  • TypeScript Functions Type
    TypeScript function types define the structure of a function, including its parameter types and return type, ensuring consistent and type-safe usage. Help validate the types of parameters passed to a function.Ensure the function returns the expected type.Improve code clarity and prevent runtime erro
    6 min read
  • TypeScript Generic Functions
    TypeScript generic functions allow you to create functions that work with various types while maintaining type safety. By using type parameters, defined within angle brackets (<T>), generics enable functions to operate on different data types without losing the benefits of TypeScript's type-ch
    3 min read
  • Swift - Function Overloading
    In Swift, a function is a set of statements clubbed together to perform a specific task. It is declared using the "func" keyword. We can also set the return type of the function by specifying the data type followed by a return arrow ("->"). Syntax: func functionName(parameters) -> returnType {
    8 min read
  • Function Overloading With Generics In TypeScript
    TypeScript has the ability to overload functions which means multiple signatures may be defined for one single function, this comes in handy when you want a function to behave in a certain way based on the provided parameters. In this article, we will be looking at how function overloading is done u
    4 min read
  • Solidity Function Overloading
    Function overloading in Solidity lets you specify numerous functions with the same name but varying argument types and numbers.Solidity searches for a function with the same name and parameter types when you call a function with certain parameters. Calls the matching function. Compilation errors occ
    1 min read
  • Syntax to create function overloading in TypeScript
    Function overloading is a feature in object-oriented programming where multiple functions can have the same name but different parameters. The parameters can differ in number, types, or both. This allows a single function name to perform different tasks based on the input parameters. Syntax: functio
    2 min read
  • How to achieve function overloading in TypeScript ?
    In this article, we will try to understand some basic details which are associated with the concept of function/method overloading, further will see how we could implement function overloading in TypeScript. Let us first understand some basic facts involved in function/method Overloading. Function/M
    2 min read
  • TypeScript void Function
    Void functions in TypeScript are functions that do not return a value. They perform actions or computations without producing a result that needs to be captured. Commonly used for side effects like logging, modifying external state, or triggering asynchronous operations, they enhance code clarity. S
    3 min read
  • TypeScript Writing Good Overloads
    In this article, we are going to learn about Writing Good Overloads in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. For writing good overloads, you should always prefer parameters with union types instead of overloads when possible beca
    3 min read
  • TypeScript unknown Function
    In TypeScript, the unknown type is used for variables whose types aren't known in advance. It ensures type safety by requiring explicit type checks or assertions before usage, preventing arbitrary operations, and promoting safer handling compared to the `any` type. Syntaxfunction gfg(input: unknown)
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences