eolas/zk/Function_overloads.md

59 lines
1.4 KiB
Markdown
Raw Permalink Normal View History

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
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}`;
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);
}
}
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}`;
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);
}
}
logSearchUnion("melon", "honey-dew");
logSearchUnion("oranges", 4);
2022-09-04 18:00:04 +01:00
```