Open In App

How to Infer Return Type from a Tuple Parameter ?

Last Updated : 19 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, inferring the return type from a tuple parameter involves deriving the type of value returned by a function based on the types of its tuple parameters. This allows the compiler to deduce the function’s output type without explicit annotation, enhancing type safety and readability.

These are the following approaches:

Approach 1: Using Conditional Type

In this approach, we are using a conditional type to infer the return type from a tuple parameter. It deconstructs the tuple, extracting the last element as the return type, ensuring accurate type inference for functions with tuple parameters.

Example: We define myReturnType to infer the return type from a tuple parameter. It applies this to myFunction, then assigns the return value of booleanReturn() to a variable, result, with the inferred type.

Javascript
type myReturnType<T extends any[]> = T extends
    [infer First, ...infer Rest, infer Return] ? Return : never;

function myFunction(...args: [number, string, boolean]):
    string {
    return "GeeksforGeeks";
}

type Result = myReturnType<Parameters<typeof myFunction>>;

function booleanReturn(): boolean {
    return true;
}
const result: Result = booleanReturn();
console.log(result);

Output:

true

Approach 2: Using ReturnType with Function Type

In this approach, we are using ReturnType with function types. It derives the return type from a function’s signature. For instance, ReturnType<typeof func> infers the return type of function func.

Example: We define myFunction returning a tuple of string and number. booleanReturn returns a value matching myFunction’s return type.

Javascript
function myFunction(...args: [number, string, boolean]):
    [string, number] {
    return [&quot;GeeksforGeeks&quot;, 18];
}

type Result = ReturnType&lt;typeof myFunction&gt;;

function booleanReturn(): Result {
    return [&quot;true&quot;, 18];
}

const result: Result = booleanReturn();

console.log(result);

Output:

[ 'true', 18 ]

Approach 3: Using Inference with Tuple Parameter

This approach utilizes TypeScript’s type inference capabilities to deduce the return type from a tuple parameter directly within the function signature. By leveraging the types of the tuple parameters, TypeScript infers the appropriate return type, enhancing code readability and reducing the need for explicit type annotations.

Example: We define a function, extractReturnType, which takes a tuple parameter and returns the last element of the tuple. The return type is directly inferred by TypeScript based on the tuple parameter provided.

JavaScript
function extractReturnType<T extends any[]>(...args: T): T[number] {
    return args[args.length - 1];
}

// Usage
const result1: string | number | boolean = extractReturnType("Hello", 42, true); 
const result2: number = extractReturnType(1, 2, 3, 4); 

console.log(result1);
console.log(result2);

Output:

true 
4 


Similar Reads

How to Infer First Element of a Tuple as a Tuple Type ?
Tuples can be represented as arrays or objects in TypeScript. This will be achieved by knowing Typescript's type system and methods such as manual inference as well as the use of the advanced type system of TypeScript. Defining a tuple type in TypeScript resembles the array syntax with the possibility to specify the type for each element position.
4 min read
What is the use of Infer Keyword in TypeScript ?
The infer keyword in TypeScript is primarily associated with conditional types and is used to capture and assign a type to a type parameter within the scope of a conditional type. It allows TypeScript to infer the type from a given expression and use it within the definition of a more complex type. Table of Content Use Case: Conditional TypesUse Ca
3 min read
How to Transform Union Type to Tuple Type in TypeScript ?
In TypeScript, conversion from union type to tuple type consists of mapping each type in the union to a position in the tuple. This process consists of using mapped types or conditional types to perform the transformation. The below methods can be implemented to accomplish this task. Table of Content Using Mapped TypesUsing Recursive Conditional Ty
3 min read
TypeScript Parameter Type Annotations
TypeScript Parameter type annotations are used to specify the expected data types of function parameters. They provide a way to explicitly define the types of values that a function expects as arguments. Parameter type annotations are part of TypeScript's static typing system, and they help catch type-related errors during development. Syntaxfuncti
2 min read
TypeScript Return Type Annotations
In this article, we are going to learn about the Return Type Annotations in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. One of the features of Typescript is Return Type Annotations which helps to explicitly declare the type of value that a function is expected to return. Return type a
2 min read
TypeScript Return type void
TypeScript, void represents the return value of functions that don’t return a value. Syntax: function functionName(parameters: ParameterType): void { // Function body // No return statement or return type annotation is needed}Example 1: In this example, function greet is the name of the function which is a void function, the name is the parameter,
1 min read
How to return the data type of variable in JavaScript ?
To return the JavaScript data type of a variable we can use the JavaScript typeof operator. In JavaScript, unlike many other programming languages, we do not specify the type of a variable while declaring it, rather the variable's type is automatically inferred based on the value it holds. In other words, JavaScript is a "dynamically typed" program
3 min read
How to Return a Union Type in TypeScript ?
In TypeScript, a union type is a powerful way to express a variable that can be one of several types. Union types are used when a function or variable is expected to support multiple types of input. Union types are defined using the pipe (|) symbol between two or more types. This indicates that a variable or return value can be any one of these typ
4 min read
How to Strongly Type the Return Value of any Function in TypeScript ?
Specifying the return type after a function's parameters with a colon ensures a consistent return value type. This enhances code reliability by enforcing expected return types. It is a fundamental feature of TypeScript that ensures functions consistently produce values of the specified type. The below methods can be used to achieve this task: Table
2 min read
How to Declare the Return Type of a Generic Arrow Function to be an Array ?
In TypeScript, declaring the return type of a generic arrow function to be an array is generally essential when we want to ensure that the function always returns the array of a particular type. This is especially necessary for maintaining type safety and maintaining consistency in our code. Declaring the return type as an array, one can avoid unin
3 min read