|
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 AssignabilityIn 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 Syntax1. Contextual Syntax:This allows assignability and does not produce errors. type FunctionType = () => void; 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 { Parameters
Examples of TypeScript Assignability of FunctionsExample 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.
Output: 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.
Output: FAQs – TypeScript Assignability of FunctionsWhy are functions with a void return type assignable to other return types?
What is the main difference between contextual and literal syntax in function assignment?
Can a function returning a value be assigned to a function type expecting void?
Is it possible to check if the returned value is used in TypeScript?
What are the practical applications of this assignability feature?
|
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |