DEV Community

ilma fauziyah
ilma fauziyah

Posted on

Typescript - Function Overloads

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:

  1. accept person’s name & address and return an id, or
  2. 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;
Enter fullscreen mode Exit fullscreen mode

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
  }
Enter fullscreen mode Exit fullscreen mode

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"
// }
Enter fullscreen mode Exit fullscreen mode

or using the second one :

findPerson('Firman', 'Kuningan Raya 11A');
// this will return string "person002" 
Enter fullscreen mode Exit fullscreen mode

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.

Reference

Top comments (0)