Explanation of returning multiple values

Can you help me understand how to specify the type when a function returns two values?

Consider this function:

const exampleFunction = (input: number) => {
  const firstValue = input;
  const innerFunction = (funcInput: number) => {
    funcInput * input;
  };
  return [firstValue, innerFunction];
};

Here is how I am calling it:

const [value, innerFunction] = exampleFunction(1);

However, TypeScript seems uncertain whether innerFunction is actually a function. Currently, it interprets it as:

number | ((funcInput: number) => void)

Is there a way to inform TypeScript that the second return value is indeed a function?

Answer №1

In order to achieve that task efficiently, you must ensure your function returns a tuple type:

To accomplish this, define your function like so:
const myFunc = (input: number): [number, (funcInput: number) => void] => { ... };
                                    // ^-----------------------------------^ 

Answer №2

To improve readability, consider creating a custom type or interface for the return value:

interface CustomType {
    value: number;
    action: (num: number) => void
}

const myFunction = (input: number): CustomType => { ... }; // The return structure will be clearer

You can also directly specify the return type in the function:

const myFunction = (input: number) => {
// ...
return {
      data,
      action
   }
};

Using tuples may not provide clear field names since they are position-based.

It's recommended to choose an approach that includes descriptive field names to avoid confusion.

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

Angular allows you to bind a Checkbox input type to be checked by default

Working on an Angular 5 application with checkboxes. Data is retrieved from the database and mapped to a JavaScript object. Having trouble configuring the 'Selected' value. Currently, all checkboxes are checked in the result. In the code below, ...

`Property cannot be redefined: __internal__deprecationWarning` detected in a Shopify Hydrogen development project

Recently, while working on my Shopify Hydrogen project using Remix and Typescript, I encountered a sudden error when running npm run dev. Everything was functioning perfectly just 5 hours ago, but after returning from dinner, the app refuses to launch. ╭ ...

What is the reason behind TypeScript compiler not throwing an error when a function's return type is defined as a number but the function actually returns undefined

Why does TypeScript not show an error when a function returns null or undefined while the function's return type is number. //gives error //Error : A function whose declared type is neither 'void' nor 'any' must return a value.ts(2 ...

What to do when calling disabled() on a FormControlName causes all form fields to become invalid?

While working with a reactive form, I have observed that setting a formControlName to disabled() can cause the entire form to become invalid. Is there a way to ensure the form remains valid even after disabling a control? console.log('Before:' ...

What might be the underlying reason for Chrome displaying a net::ERR_FAILED error when attempting to make a request from a Vue frontend to a C# API using Axios?

I have a C# Backend+API that I interact with from my Vue Application using axios to make requests. In the C# code, there is an endpoint that looks like this: // GET: api/Timezone public HttpResponseMessage GetTimezoneData() { ...

Ways to effectively leverage the types from lib.d.ts?

It appears that the issue at hand is related to WebStorm IDE. I have reported it to WebStorm and you can track the progress here. Currently, I am working with Angular 2 and TypeScript 2. I am wondering how to explicitly utilize the location from lib.d.ts ...

Error TS2339: The property 'mock' is not found on the type '(type: string) => Promise'. Unable to create a mock for SQS Queue.sendMessage()

I am attempting to simulate a call to the SQS method sendMessage() that is used in the System Under Test (SUT) like this: private async pushJobIntoQueue(network: Network) { await this.contactInteractionsQueue.sendMessage( JSON.stringify({ ...

How to reference an object from an external file in TypeScript using Ionic 2 and Angular 2

I am currently developing a mobile application with Ionic2 and have integrated a simple online payment service called Paystack for processing payments. The way it operates is by adding a js file to your webpage and then invoking a function. <script> ...

Could one potentially assign number literals to the keys of a tuple as a union?

Imagine having a tuple in TypeScript like this: type MyTuple = [string, number]; Now, the goal is to find the union of all numeric keys for this tuple, such as 0 | 1. This can be achieved using the following code snippet: type MyKeys = Exclude<keyof ...

Include a query parameter each time a page is added to bookmarks

Is there a way to automatically add a query parameter to a page URL when bookmarked using Chrome? For example, if I bookmark https://www.example.com, can it be saved as https://www.example.com/?bookmarked? I'm thinking I might need to use JavaScript ...

Color changes on mat-calendar when hovering

Is it possible to change the hover color of the Mat-calender element? I managed to do so using this CSS code: .mat-calendar-body-cell-content:hover { background-color:#something } The issue is that when hovering the cursor in the corner of the cell, the ...

A guide on seamlessly incorporating cornerstone3d Examples into your React application

I'm currently working on incorporating the examples found at into a react application, but I'm facing some challenges. Here's what I've done so far: Created a new react app using typescript template: npx create-react-app my-app --tem ...

What could be causing TypeScript to identify my immer draft as undefined?

I'm completely lost, can someone please help me with this issue: Currently, I am trying to update a typed configuration. Within my Provider component: const [data, setData] = useImmer<typeof INITIAL_CONFIG>(INITIAL_CONFIG) ... function updateF ...

Building a unique React component with TypeScript that showcases a custom Grid item property

I'm attempting to display multiple items using a custom property for a Grid component. I'm unsure of the process for accomplishing this in a React component using TypeScript. export interface IComponentItem { width: 1 | 2 | 3 | 4 | 5 | 6 | 7 | ...

Guide on creating a Jasmine test for a printer utility

Currently, I am working on writing a Jasmine test for the print function shown below: printContent( contentName: string ) { this._console.Information( `${this.codeName}.printContent: ${contentName}`) let printContents = document.getElementById( c ...

The Tools of the Trade: TypeScript Tooling

Trying out the amazing Breeze Typescript Entity Generator tool but encountering an error consistently. Error: Experiencing difficulty in locating the default implementation of the 'modelLibrary' interface. Options include 'ko', 'b ...

Issue with CDK pipeline: Unable to configure lambda layer across various stages in the pipeline stack

When trying to set multiple stages with the same stack in a CDK pipeline, I encountered an error during bootstrapping of my CDK project: C:\dev\aws-cdk\node_modules\aws-cdk-lib\aws-lambda\lib\code.ts:185 throw new E ...

Internationalization in Angular (i18n) and the powerful *ngFor directive

Within my Angular application, I have a basic component that takes a list of strings and generates a radio group based on these strings: @Component({ selector: 'radio-group', templateUrl: `<div *ngFor="let item of items"> ...

Excessive geolocation position responses in Angular 5

I am trying to implement an Angular 5 component that will continuously fetch my current location every 3 seconds if it has changed. Here is a snippet of my code: export class WorkComponent implements OnInit { constructor(private userService: UserService ...

Encountering a NgForm provider error in Angular 4.4.6 development mode

UPDATE: Identifying the root of the issue has led me to search for a suitable solution. NOTE: This complication is specific to development mode (not production, and not utilizing AOT). The "Update" resolution I am implementing can be found here. In an a ...