There are times we need to create a function that can be implemented multiple ways : accept multiple types of arguments and/or has multiple return types.
This can be achieved by declaring function overloads and then declaring the actual implementation of the function based on the overloads.
What is Overload Signature?
A function overload only declares function's parameter and return type but doesn't include function body.
What is Implementation Signature?
This is where we actually implement the overload signatures. Implementation signature contains generalized function parameters and return type followed by function body.
How to
Let's create a ‘findPerson’ function that can:
- accept person’s name & address and return an id, or
- accept the person’s id and return an object.
Here’s how we declare two overload signatures for our findPerson function.
// First overload signature
function findPerson(
name: string,
address: string
): string;
// Second overload signature
function findPerson(id: string): Person;
No matter how many overload signatures we have, we can only have one implementation signature. So we need to make sure that the implementation is general and relevant to both of the overload signatures.
const people = [
{
id: "person001",
name: "Alicia",
address: "Soedirman Street 120"
},
{
id: "person002",
name: "Firman",
address: "Kuningan Raya 11A"
}
];
function findPerson(
nameOrId: string,
address: string
): string | Person {
let personFoundOrId = null
if (address === undefined){
// Implementation for first overload signature
personFoundOrId = people.find((person:Person) => {
person.id === nameOrId
}
} else {
// Implementation for second overload signature
const personFound = people.find((person:Person) => {
person.name === nameOrId && person.address === address
}
personFoundOrId = personFound?.id
}
return personFoundOrId
}
Result
This is how you call the findPerson function using the firest overload :
findPerson('person001');
// this will return an object
// {
// id: "person001",
// name: "Alicia",
// address: "Soedirman Street 120"
// }
or using the second one :
findPerson('Firman', 'Kuningan Raya 11A');
// this will return string "person002"
Conclusion
- Function overload enables a function having more than one implementation.
- To make this works, implementation signature must be compatible with each of the overload signatures.
Top comments (0)