2022-04-23 13:26:53 +01:00
|
|
|
---
|
|
|
|
tags:
|
|
|
|
- typescript
|
|
|
|
---
|
|
|
|
|
2024-10-19 10:00:02 +01:00
|
|
|
# Function overloads
|
2022-04-23 13:26:53 +01:00
|
|
|
|
2024-02-02 15:58:13 +00:00
|
|
|
Function overloading is not a feature of JavaScript but something close to it
|
|
|
|
can be achieved with TypeScript. It proceeds by defining multiple function types
|
|
|
|
(defined above the function) that may serve as the actual function's parameters.
|
|
|
|
Then with the actual function, you leave the changeable parameters open as
|
|
|
|
optional unions and/or `unknown` :
|
2022-04-23 13:26:53 +01:00
|
|
|
|
2022-09-04 18:00:04 +01:00
|
|
|
```ts
|
2022-04-23 13:26:53 +01:00
|
|
|
// First oveload type:
|
|
|
|
function logSearch(term: string, options?: string): void;
|
|
|
|
|
|
|
|
// Second overload type:
|
|
|
|
function logSearch(term: string, options?: number): void;
|
|
|
|
|
|
|
|
// Implementation:
|
|
|
|
function logSearch(term: string, p2?: unknown) {
|
|
|
|
let query = `https://searchdatabase/${term}`;
|
2024-02-02 15:58:13 +00:00
|
|
|
if (typeof p2 === "string") {
|
2022-04-23 13:26:53 +01:00
|
|
|
query = `${query}/tag=${p2}`;
|
|
|
|
console.log(query);
|
|
|
|
} else {
|
|
|
|
query = `${query}/page=${p2}`;
|
|
|
|
console.log(query);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-02 15:58:13 +00:00
|
|
|
logSearch("apples", "braeburn");
|
|
|
|
logSearch("bananas", 3);
|
2022-09-04 18:00:04 +01:00
|
|
|
```
|
2022-04-23 13:26:53 +01:00
|
|
|
|
2022-09-04 18:00:04 +01:00
|
|
|
```ts
|
2022-04-23 13:26:53 +01:00
|
|
|
// First overload type:
|
|
|
|
function logSearchUnion(term: string, options?: string): void;
|
|
|
|
|
|
|
|
// Second overload type:
|
|
|
|
function logSearchUnion(term: string, options?: number): void;
|
|
|
|
|
|
|
|
// Implementation:
|
|
|
|
function logSearchUnion(term: string, p2?: string | number) {
|
|
|
|
let query = `https://searchdatabase/${term}`;
|
2024-02-02 15:58:13 +00:00
|
|
|
if (typeof p2 === "string") {
|
2022-04-23 13:26:53 +01:00
|
|
|
query = `${query}/tag=${p2}`;
|
|
|
|
console.log(query);
|
|
|
|
} else {
|
|
|
|
query = `${query}/page=${p2}`;
|
|
|
|
console.log(query);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-02 15:58:13 +00:00
|
|
|
logSearchUnion("melon", "honey-dew");
|
|
|
|
logSearchUnion("oranges", 4);
|
2022-09-04 18:00:04 +01:00
|
|
|
```
|