Open In App

TypeScript Assignability of Functions

Last Updated : 22 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In this article, we will explore the concept of assignability of functions in TypeScript. Specifically, we will discuss how functions with a return type of void can be assigned to function types with other return types, including those that return values.

Understanding Assignability

In TypeScript, functions with a void return type are assignable to function types with different return types. This means you can assign a function that does not return a value (void) to a variable or parameter expecting a function that returns a different type of value. However, TypeScript does not check if the returned value is being used when performing such assignments.

Contextual Syntax vs. Literal Syntax

1. Contextual Syntax:

This allows assignability and does not produce errors.

type FunctionType = () => void;
const functionName: FunctionType = () => {
// Function body
};

2. Literal Syntax:

This will give an error if the function does not match the expected return type.

function functionName(parameter1: Type1, parameter2: Type2, ...): void {
// Function body
}

Parameters

  • functionType: custom name for function type.
  • functionName: The name of the function of the type defined.
  • : void: Indicates the return type of void, meaning the function doesn't return a meaningful value.

Examples of TypeScript Assignability of Functions

Example 1: In this example, we assign a void function to a function returning a string value. When the return value of the f1 function is assigned to another variable, it retains the type void.

JavaScript
type voidFunc = () => void;
 
const f1: voidFunc = () => {
  return "GeeksforGeeks";
};
 
const gfg = f1();
console.log(gfg)
console.log(typeof gfg)

Output:

z1

Example 2: In this example, we will see even though Array.prototype.push returns a number and the Array.prototype.forEach method expects a function with a return type of void, the code is valid.

JavaScript
const gfg = 
    ["Java","C++", "Python","React","Typescript"];
const course = [];
 
gfg.forEach((el) => course.push(el));
console.log(course)

Output:

z9



Similar Reads