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:
Interesting Facts About Generics in TypeScript
Next article icon

Interesting Facts About Functions in TypeScript

Last Updated : 19 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript enhances JavaScript functions with strong typing, better inference, and advanced features, making code safer, more readable, and more scalable. Understanding its function-related capabilities can greatly improve development efficiency.

1. TypeScript Infers Function Argument Types

TypeScript can automatically guess the types of function arguments based on how they are used, especially in callbacks.

JavaScript
const numbers = [1, 2, 3]; numbers.forEach((num) => console.log(num.toFixed(2))); // TypeScript infers `num` as a number 

2. Typing this in Callback Functions

You can specify the type of this in callback functions to ensure it behaves as expected.

JavaScript
interface Button {     onClick: (this: Button, event: Event) => void; }  const button: Button = {     onClick() {         console.log(`Button clicked: ${this}`); // `this` is correctly typed as `Button`     }, }; 

3. Function Overloading with Different Return Types

TypeScript allows you to define multiple function signatures with different return types based on input types.

JavaScript
function parseInput(input: string): string; function parseInput(input: number): number; function parseInput(input: string | number): string | number {     if (typeof input === "string") {         return `Parsed string: ${input}`;     } else {         return input * 2; // Return a number     } }  console.log(parseInput("Hello")); // Parsed string: Hello console.log(parseInput(10));     // 20 

4. Strongly Typed Rest Parameters

Rest parameters can be typed as tuples to enforce a specific structure.

JavaScript
function logDetails(...details: [string, number]): void {   console.log(`Name: ${details[0]}, Age: ${details[1]}`); }  logDetails("Alice", 25); // Name: Alice, Age: 25 

5. Functions Can Return Different Types

TypeScript functions can return different types based on the input.

JavaScript
function process(value: string | number) {   return typeof value === "string" ? value.toUpperCase() : value * 2; } console.log(process("hello")); // "HELLO" console.log(process(5)); // 10   

6. Function Currying in TypeScript

Currying allows you to create reusable functions by returning another function.

JavaScript
function add(a: number): (b: number) => number {     return (b: number) => a + b; }  const addFive = add(5); console.log(addFive(10)); // 15 

7. Function Types for Callbacks

You can define function types for callbacks to improve readability.

JavaScript
type ClickHandler = (event: MouseEvent) => void; const handleClick: ClickHandler = (event) => {   console.log(event.clientX, event.clientY); }; document.addEventListener("click", handleClick); 

8. Generic Functions with Constraints

Generic functions can enforce constraints to ensure the input meets specific conditions.

JavaScript
function logLength<T extends { length: number }>(arg: T): void {     console.log(arg.length); }  logLength("Hello"); // 5 logLength([1, 2, 3]); // 3 

9. Using void as a Return Type

The void return type indicates that a function does not return a value.

JavaScript
function logMessage(message: string): void {     console.log(message);     // No return statement is needed }  logMessage("Hello, TypeScript!"); 



Next Article
Interesting Facts About Generics in TypeScript

T

tanmxcwi
Improve
Article Tags :
  • TypeScript

Similar Reads

  • Interesting Facts About Generics in TypeScript
    TypeScript generics provide a powerful way to create reusable, type-safe components and functions that work with multiple types. They improve flexibility, reduce redundancy, and ensure strict type constraints without sacrificing reusability. 1. Generics Make Functions FlexibleGenerics allow you to c
    3 min read
  • Interesting Facts About TypeScript Basics
    TypeScript is a statically typed superset of JavaScript that brings powerful tools and features to modern web development. While it may seem like just an extension of JavaScript, TypeScript introduces concepts that significantly improve code quality and maintainability. 1. TypeScript is a Superset o
    3 min read
  • Interesting Facts About Modules and Namespaces in TypeScript
    Modules and namespaces in TypeScript help organize and encapsulate code, preventing naming conflicts and improving maintainability. Modules use the ES6 import/export system, while namespaces provide internal organization within a single file. Here are some interesting facts about them: 1. TypeScript
    3 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
  • Interesting Facts About Object Types and Interfaces in TypeScript
    TypeScript enhances object types and interfaces with strong typing, extendibility, and dynamic features, making code more structured and maintainable. Mastering these concepts improves scalability, flexibility, and type safety in applications. 1. Interfaces Can Describe FunctionsInterfaces in TypeSc
    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 - Generic Functions and Generic Classes
    Generics in TypeScript enable functions and classes to work with multiple data types while ensuring type safety. Generic functions provide reusable logic that adapts to various inputs, while generic classes help define flexible and type-safe structures. Generic FunctionsA generic function allows you
    2 min read
  • How to Type an Async Function in TypeScript ?
    An asynchronous function allows your code to do multiple things at once. It doesn't block the execution of the rest of your code while waiting for a long task (like reading a file, making an API request) to finish. Instead, it returns a Promise, making it easier to handle operations that might take
    3 min read
  • Explain about rest parameters and arguments in TypeScript
    In this article, we will try to understand all the basic facts or details which are associated with Rest Parameters and Arguments in TypeScript. Rest Parameters: Rest Parameter allows us to accept zero or more arguments of the specified type.A function (or a method) has only one rest parameter.This
    3 min read
  • TypeScript Declaring this in a Function
    TypeScript Declaring this in a Function, where 'this' in TypeScript refers to an object's current instance in a function, granting access to its properties and methods. It's essential to declare 'this' types for safety while using functions in TypeScript and properly declare the type of 'this'. Synt
    2 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