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 –
- Function name is same
- Number of parameters are different in each overload
- If number of parameters is same the their type must be different
- 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 !!
Alan
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?
Alain
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…
Basavaraj
how overload methods within the class
Lokesh Gupta
Method overloading happen within class. You override a method in child class.