Using Typescript to create a union of functions

There are two different types of functions: one that returns a string and the other that returns a Promise<string>. Now, I am looking to create a function that can wrap both types, but I need to be able to distinguish between them when invoking the fn function.

type FuncTypes = (...args: any[]) => string | Promise<string>

function callFunc(fn: FuncTypes, ...args: any[]) {
  // Need to differentiate if fn returns a string or a Promise<string>
  // If fn returns a string
    return new Promise<string>(r => r(fn.call(this, ...args)))
  // If fn returns a Promise
    return fn.call(this, ...args)
}

Another scenario is overloading:

type FuncA = (...args: any[]) => string
type FuncB = (...args: any[]) => Promise<string>

function callFunc(fn: FuncA, ...args: any[]): Promise<string>
function callFunc(fn: FuncB, ...args: any[]): Promise<string>
function callFunc(fn: any, ...args: any[]): Promise<string> {
  // If fn is an instance of FuncA
  // Do something
  // Else if fn is an instance of FuncB
  // Do something
}

While we can use

const returned = fn(..args); typeof returned === 'string'
to check the return type, this is not a universal solution. When the function type is
() => AnInterface|AnotherInterface
, it becomes challenging to determine the return type using typeof or instanceof.

Is there a general approach to distinguishing these function types, or should I create separate functions for each type?

Answer №1

When dealing with a specific scenario

In this particular case, we encounter two different types of functions - one that returns a string and another that returns a Promise. The challenge lies in creating a function that can handle both cases while distinguishing between them during invocation.

For this particular situation, the solution could simply be:

function callFunc(fn: FuncTypes, ...args: any[]) {
    return <Promise<string>>Promise.resolve(fn.call(this, ...args));
}

If the function being called returns a promise, it will await that promise before resolving it; if not, a fulfilled promise with the returned value of the function will be generated.

When looking at the broader picture

Is there a universal method to differentiate between these function types?

Unfortunately, such distinction cannot be made at runtime unless specified in advance. TypeScript's typing information only applies at compile-time.

Should I create separate functions for each type instead?

Creating distinct functions for each type is likely the most effective approach.

An alternative would involve annotating the functions by adding a property indicating their return type:

function delay(ms: number, value: string): Promise<string> {
    return new Promise<string>(resolve => setTimeout(resolve, ms, value));
}
(<any>delay).returnValue = "Promise<string>";

This method however duplicates the type information, leading to redundancy in your code.

Hence, the recommended solution remains to create separate functions for each function type.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

a guide to transforming data into a string with json using angular

I am struggling to figure out how to bind my form data into a JSON string. My situation involves using a string field in the database and saving checkbox values in a single database column using JSON. I have created an HTML form, but I am unsure of how to ...

Is there a way to tally up the overall count of digits in a number using TypeScript?

Creating a number variable named temp in TypeScript: temp: number = 0.123; Is there a way to determine the total count of digits in a number (in this case, it's 3)? ...

Variable not accessible in a Typescript forEach loop

I am facing an issue with a foreach loop in my code. I have a new temp array created within the loop, followed by a nested foreach loop. However, when trying to access the temp array inside the nested loop, I encounter a "variable not available" error. le ...

The argument labeled as 'shop' does not fit the criteria for the parameter 'items' or 'cart'

I've been doing some research but haven't had any luck finding a solution. I'm fairly new to Angular and currently working on a webstore project. I followed a tutorial, but encountered an error along the way. import { select, Store } from & ...

What is the best method for incorporating an Angular Component within a CSS grid layout?

I recently started learning Angular and am currently working on a project that requires the use of a CSS grid layout. However, I'm facing an issue with inserting a component inside a grid area specified by grid-area. My attempt to achieve this in app ...

Issue with typings in TypeScript is not being resolved

I have integrated this library into my code Library Link I have added typings for it in my project as follows Typings Link I have included it in my .ts file like this import accounting from "accounting"; I can locate the typings under /node_modules ...

The onNodeContextMenuSelect function does not seem to be functioning properly within the p-tree

<p-tree [value]="files" selectionMode="single" (onNodeContextMenuSelect)="showContect($event)" > </p-tree> Whenever I right click, the event doesn't seem to be triggering. Instead, the default browser c ...

Updating the React State is dependent on the presence of a useless state variable in addition to the necessary state variable being set

In my current setup, the state is structured as follows: const [items, setItems] = useState([] as CartItemType[]); const [id, setId] = useState<number | undefined>(); The id variable seems unnecessary in this context and serves no purpose in my appl ...

Transforming TypeScript snapshot data in Firebase Cloud Functions into a string format for notification purposes

I've encountered the following code for cloud functions, which is intended to send a notification to the user upon the creation of a new follower. However, I'm facing an issue regarding converting the snap into a string in order to address the er ...

What causes the unexpected behavior of the rxjs share operator when used with an observable in a service?

I attempted to utilize the rxjs share operator in two distinct manners. Implementing it in the component Component: constructor() { const obs1 = interval(1000).pipe( tap(x => console.log('processing in comp1')), map(x => x ...

External JavaScript files cannot be used with Angular 2

I am attempting to integrate the twitter-bootstrap-wizard JavaScript library into my Angular 2 project, but I keep encountering the following error: WEBPACK_MODULE_1_jquery(...).bootstrapWizard is not a function I have created a new Angular app using a ...

Curious about the missing dependencies in React Hook useEffect?

I'm encountering the following issue: Line 25:7: React Hook useEffect has missing dependencies: 'getSingleProductData', 'isProductOnSale', and 'productData'. Either include them or remove the dependency array react-hoo ...

When converting an object into a specific type, the setter of the target type is not invoked

Imagine a scenario with a class structured like this: class Individual { private _name: string; get Name(): string { return this._name; } set Name(name: string) { this._name = name; } } Upon invoking HttpClient.get<Individual>(), it retrieve ...

How can I arrange selected options at the top in MUI autocomplete?

I am currently working with mui's useAutocomplete hook https://mui.com/material-ui/react-autocomplete/#useautocomplete Is there a way to programmatically sort options and place the selected option at the top using JavaScript sorting, without resorti ...

selective ancestor label Angular 8

I am looking for a way to place my content within a different tag based on a specific condition. For instance, I need my content to be enclosed in either a <table> or <div> depending on the condition. <table|div class="someClass" ...

Issue with setting value using setState in TypeScript - what's the problem?

Every time I attempt to update the value of currentRole, it appears highlighted in red. Here is a screenshot for reference: const Container: React.FC<ContainerProps> = ({ children }) => { const [role, setRole] = useState<string>(); useE ...

Binding an ID to an <ion-textarea> in Ionic 3

Can an ID be assigned to an ion-textarea? For example: <ion-textarea placeholder="Enter your thoughts" id="thoughtsBox"></ion-textarea> Thank you very much ...

The issue lies in attempting to assign an 'Observable<number[]>' to a parameter expecting an 'Observable<ProjectObject[]>'. This obstacle must be overcome in order to successfully create a mock service

I am currently working on setting up a mock service for unit testing, but I am facing an issue where the observable is not returning the expected fake value. Can someone please assist me in resolving this problem and also explain what might be wrong with m ...

Mocking is not working for request scoped injection

I'm encountering an issue with mocking the return value of a provider, as it seems to be clearing out the mock unexpectedly. Module1.ts @Module({ providers: [Service1], exports: [Service1], }) export class Module1 {} Service1.ts @Injectable({ ...