TypeScript Function or Method Overloading

In TypeScript, function overloading, or method overloading, is the ability to create multiple methods with the same name and a different number of parameters or types.

So essentially, method overloading is allowed when –

  1. Function name is same
  2. Number of parameters are different in each overload
  3. If number of parameters is same the their type must be different
  4. All overloads must have same return type

Also note that, function implementation must be compatible with all the overloaded signatures. It should always be the last in the list, and take the any type or a union type as the type of its parameters.

Function Overloading Example

Suppose we are creating a function which will return the Employee type based on different parameters such as id, email, name or their combination. let’s create overloaded functions for this requirement.

class Employee {}

function getEmployee(id: number): Employee; 					//Overload 1
function getEmployee(email: string): Employee; 					//Overload 2
function getEmployee(email: number, name: string): Employee; 	//Overload 3

//function getEmployee(name: string): Employee; 				//Error - Conflict with Overload 2

//Implement the function
function getEmployee (paramOne: string | number, paramTwo?: string ): Employee { 
	
	let employee: Employee;

    if( typeof paramOne === 'number') {
    	//Logic for overload 1
	} else if( typeof paramTwo != 'undefined') {
		//Logic for overload 3
	} else {
		//Logic for overload 2
	}

	return employee;
} 

Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

4 thoughts on “TypeScript Function or Method Overloading”

  1. Will intelliSense take advantage of it? I mean: If I start to type getEmployee(323, will the intelliSense show me the version which takes a number as param?

    Reply
  2. I think you meant
    function getEmployee(email: string, name: string)
    otherwise:
    if ( typeof paramOne === ‘number’) {
    //Logic for overload 1
    }
    could be used for case 3 as well…

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.