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 unknown Function
Next article icon

TypeScript Function

Last Updated : 11 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript functions are blocks of reusable code designed to perform specific tasks. They support object-oriented programming principles like classes and polymorphism. Functions can include type annotations for parameters and return values, enhancing code clarity, safety, and maintainability.

Syntax

function functionName(arg: argType) {     //function Body }

Where:

  • functionName: It is the name of the function
  • arg: Argument Name
  • argType: Type of the argument

TypeScript Function Types

Parameter type annotations

Parameter type annotations in TypeScript specify the type of each function parameter, ensuring the function receives arguments of the correct type.

Example: In this example we defines a greet function that takes a name parameter of type string and logs a greeting message.

JavaScript
function greet(name: string): void {     console.log(`Hello, ${name}`); } greet("Alice"); 

Output:

Hello, Alice

Return type annotations

We can write the return type of the function post parameter list. This is called Return type annotation.

Example: In this example we defines an add function that takes two number parameters and returns their sum.

JavaScript
function add(a: number, b: number): number {     return a + b; } console.log(add(2, 3)); 

Output:

5

Functions Which Return Promises

Functions that return promises in TypeScript specify Promise<Type> as the return type, indicating asynchronous operations that return a value of the specified type.

Example: In this example we defines an async function greet that returns a Promise with a string.

JavaScript
async function greet(): Promise<string> {     return ("Hello, GeeksforGeeks!!"); } greet().then(     (result) => {         console.log(result)     } ) 

Output:

Hello, GeeksforGeeks!!

Anonymous Function

An anonymous function is a nameless function defined at runtime and stored in a variable. It accepts inputs, returns outputs, and can be called using the variable's name.

Example: In this example we defines an anonymous function to calculate the square of a number and assigns it to the variable square.

JavaScript
const square = function(num: number): number {     return num * num; }; console.log(square(4)); 

Output:

16

Conclusion

In this article, we explored various types of TypeScript functions, including parameter type annotations, return type annotations, functions returning promises, and anonymous functions. These features enhance code clarity, safety, reusability, and maintainability, making it easier to write and manage TypeScript code.


Next Article
TypeScript unknown Function

A

abhiisaxena09
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks Premier League 2023

Similar Reads

  • 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 Functions Type
    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 erro
    6 min read
  • TypeScript unknown Function
    In TypeScript, the unknown type is used for variables whose types aren't known in advance. It ensures type safety by requiring explicit type checks or assertions before usage, preventing arbitrary operations, and promoting safer handling compared to the `any` type. Syntaxfunction gfg(input: unknown)
    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 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 Assertion functions
    TypeScript Assertion functions are nothing but the functions that allow us to mainly create the custom type guards that assert the type of a value on our specific criteria. The most suitable use of Assertion Functions is when we are working with the more complex data structures. Syntax:function asse
    3 min read
  • TypeScript Constraints
    TypeScript constraints are used in generic type declarations to restrict the types that can be used as type arguments for the generic. Constraints allow you to specify that a generic type parameter must meet certain criteria, such as implementing a particular interface, having a specific method, or
    2 min read
  • PHP gettype() Function
    The PHP gettype() function returns the type of a variable as a string. It identifies the variable's data type, such as string, integer, array, boolean, etc., allowing developers to check and handle different data types dynamically. Syntax: string gettype ( $var )Parameter: This function accepts a si
    3 min read
  • Functions in JavaScript
    Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs. [GFGTABS] JavaScript function sum(x, y) { return x + y; } console.log(sum(6, 9)); [/GFGTABS]Output1
    5 min read
  • 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
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