Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
TypeScript Anonymous Functions Type
Next article icon

TypeScript Functions Type

Last Updated : 22 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript function types define the structure of a function, including its parameter types and return type, ensuring consistent and type-safe usage.

  • Help validate the types of parameters passed to a function.
  • Ensure the function returns the expected type.
  • Improve code clarity and prevent runtime errors.
JavaScript
function add(a: number, b: number): number {     return a + b; } 

Parameters:

  • function: The keyword used to create a function.
  • functionName: Name of the function based on its functionality.
  • param1, param2: Parameters listed in the function definition.
  • type1, type2: Types of the parameters.
  • value/expression: The return value, which can be a value or expression.
  • returnType: The return type of the function.

There are several types of functions in TypeScript, which are listed below. We will explore these function types along with their basic implementations and examples.

1. Named Function

In TypeScript, functions are defined and called by their name. They include types for parameters and return values.

Syntax

function functionName([args: type]): type { }
TypeScript
function add(a: number, b: number): number {     return a + b; }  console.log(add(3, 4)); 
  • Takes two number parameters and returns their sum.
  • The return type of the function is explicitly specified as number.

Output:

7

2. Anonymous Function

An anonymous function in TypeScript is a function without a specific name, often defined inline, useful for one-off or small tasks where a named function isn't needed. The function call can be made using the variable to which it is assigned.

Syntax

const variableName = function([args: type]): type { }
TypeScript
const subtract = function(a: number, b: number): number {     return a - b; }  console.log(subtract(5, 2)); 
  • Declares an unnamed function assigned to subtract.
  • The function accepts two numbers and returns their difference.

Output:

3

3. Arrow Functions

Arrow functions in TypeScript are concise function expressions using the => syntax. They retain the parent scope's this and are often used for short, simple functions.

Syntax

const variableName = ([args: type]): type => expression;
TypeScript
const multiply = (a: number, b: number): number => a * b;  console.log(multiply(2, 5)); 
  • Uses the arrow function syntax for simplicity and concise code.
  • Multiplies two numbers and returns the result.

Output:

10

4. Optional and Default Parameters in Functions

Optional parameters in TypeScript allow you to specify function parameters that may be omitted when calling the function. Default parameters provide default values if no argument is passed.

Syntax

function functionName(arg1: type, arg2?: type): type { }
TypeScript
function greet(firstName: string, lastName: string = "Doe"): string {     return `Hello, ${firstName} ${lastName}`; }  console.log(greet("John")); console.log(greet("Joe", "Smith"));  
  • lastName is optional with a default value of "Doe".
  • If a value is provided for lastName, it overrides the default.

Output:

Hello, John Doe
Hi, Joe Smith

5. Return Type

The return type in TypeScript specifies the data type a function should return. When we expect a function to return a particular type of value like either a string or a number, we can specify return types for functions.

Syntax

function functionName(parameters: parameterTypes): returnType {
// Function body
return value; // Returns a value of 'returnType'
}

Example: Here is the basic example of Return type function in typescript.

TypeScript
function square(num: number): number {     return num * num; }  console.log(square(4)); 
  • The square function explicitly defines its return type as number.
  • Calculates the square of the input number and returns the result.

Output:

16

6. Void Return Type

In TypeScript, the void return type indicates that a function doesn't return any value. It's often used for functions that perform actions without producing a result.

Syntax

function functionName(parameters: parameterTypes): void {
// Function body
// No 'return' statement or 'return;' is used
}
TypeScript
function logMessage(message: string): void {     console.log(message); }  logMessage("Hello, Rahul!"); 
  • The logMessage function performs an action but does not return any value.
  • Commonly used for logging or side effects.

Output:

 Hello, Rahul!

7. Rest Parameters

Rest parameters in TypeScript allow a function to accept a variable number of arguments of the same type, collecting them into an array for easy processing within the function.

Syntax

function functionName(...args: type): type { }
TypeScript
function sum(...numbers: number[]): number {     return numbers.reduce((acc, curr) => acc + curr, 0); }  console.log(sum(1, 2, 3, 4, 5)); 
  • Collects multiple numeric arguments into an array.
  • Uses reduce to calculate the sum of all elements.

Output:

15

8. Function Overloading

Function overloading in TypeScript enables defining multiple function signatures for a single function, allowing it to accept different parameter types or counts while providing type safety.

Syntax

function functionName(arg1: type, arg2: type): type;
function functionName(arg1: type, arg2: type, arg3: type): type;
function functionName(...args: any[]): any {
// Implementation
}
TypeScript
function greet(person: string): string; function greet(person: string, age: number): string; function greet(person: string, age?: number): string {     if (age !== undefined) {         return `Hello, ${person}, you are ${age} years old!`;     }     return `Hello, ${person}!`; }  console.log(greet("Anne")); console.log(greet("John", 30));  
  • Handles both single and dual-parameter calls.
  • Differentiates functionality based on the number of arguments provided.

Output:

Hello, Anne!
Hello, John, you are 30 years old!

9. Callback Function

A callback function is a function that can be passed as an argument to another function and is executed when a specific event or task is completed. Callbacks are commonly used in asynchronous operations, such as handling the result of a network request or responding to user interactions.

Syntax

type callBackType = (callBackFunctionName: type) => returnType;

Example: In this example, two number type(a,b) parameters and a callback function(result) is passed to perform Operation function.

TypeScript
function performOperation(a: number, b: number, callback: (result: number) => void): void {     let result = a + b;     callback(result); }  performOperation(3, 4, (result) => {     console.log(result); }); 
  • The performOperation function takes two numbers and a callback function as arguments.
  • The callback is invoked with the result of adding the two numbers.

Output:

7

Best Practices for Using TypeScript Function Types

  • Always Specify Return Types: Clearly define the return type for better readability and error prevention.
  • Use Optional and Default Parameters Sparingly: Provide defaults only when it simplifies usage or prevents common errors.
  • Prefer Arrow Functions for Callbacks: Use arrow functions for cleaner syntax and to maintain this context.

Next Article
TypeScript Anonymous Functions Type
author
julietmaria
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks Premier League 2023

Similar Reads

  • TypeScript Anonymous Functions Type
    In TypeScript, an Anonymous Function Type defines a function without a specific name, specifying parameters and return types. This allows for flexible and reusable function definitions, enabling the assignment of functions to variables and the use of type annotations for parameters and return values
    3 min read
  • TypeScript Generic Functions
    TypeScript generic functions allow you to create functions that work with various types while maintaining type safety. By using type parameters, defined within angle brackets (<T>), generics enable functions to operate on different data types without losing the benefits of TypeScript's type-ch
    3 min read
  • TypeScript Assertions Type
    TypeScript Assertions Type, also known as Type Assertion, is a feature that lets developers manually override the inferred or expected type of a value, providing more control over type checking in situations where TypeScript's automatic type inference may not be sufficient. Syntax let variableName:
    2 min read
  • TypeScript Function Type Expressions
    In this article, we are going to learn about TypeScript Function Type Expressions in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, a function type expression represents the type of a function, including its parameter types
    3 min read
  • TypeScript Conditional Types
    In TypeScript, conditional types enable developers to create types that depend on a condition, allowing for more dynamic and flexible type definitions. They follow the syntax T extends U ? X : Y, meaning if type T is assignable to type U, the type resolves to X; otherwise, it resolves to Y.Condition
    4 min read
  • What is the Function type in TypeScript ?
    TypeScript is a JavaScript-based programming language with a typed syntax. It provides improved tools of any size. It adds extra syntax to JavaScript. This helps in facilitating a stronger interaction between you and your editor. It also helps in catching the mistakes well in advance.  It uses type
    3 min read
  • Data types in TypeScript
    In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity. Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Pri
    3 min read
  • TypeScript void Function
    Void functions in TypeScript are functions that do not return a value. They perform actions or computations without producing a result that needs to be captured. Commonly used for side effects like logging, modifying external state, or triggering asynchronous operations, they enhance code clarity. S
    3 min read
  • TypeScript Function Overloads
    TypeScript function overloads enable defining multiple signatures for a single function, allowing it to handle various parameter types or counts. Enhances type safety by ensuring correct argument handling.Improves code flexibility and readability.[GFGTABS] JavaScript function greet(person: string):
    3 min read
  • TypeScript any Type
    In TypeScript, any type is a dynamic type that can represent values of any data type. It allows for flexible typing but sacrifices type safety, as it lacks compile-time type checking, making it less recommended in strongly typed TypeScript code. It allows developers to specify types for variables, f
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences