Typescript Functions

Level : Advanced
Mentor: Shailendra Chauhan
Duration : 00:01:45

Named Function:

Named functions are defined with a specific name and can be called using that name. They are typically used for reusable blocks of code.


function greet(name: string): string {
  return `Hello, ${name}!`;
const message = greet("Alice");
console.log(message); // Output: Hello, Alice!

Function Expression:

Function expressions involve defining a function within an expression. They can be assigned to variables and passed around as values.


const add = function (a: number, b: number): number {
  return a + b;
const result = add(3, 5);
console.log(result); // Output: 8

Arrow Function:

Arrow functions are a concise way to write functions in TypeScript, especially useful for anonymous functions and when you want to maintain the lexical context (this).


const multiply = (a: number, b: number): number => a * b;
const product = multiply(4, 6);
console.log(product); // Output: 24

Function Parameters:

Function parameters are used to pass values into functions. They can have types and be optional or have default values.


function greetWithMessage(name: string, message: string = "Hello"): string {
  return `${message}, ${name}!`;
const welcome = greetWithMessage("Bob");
console.log(welcome); // Output: Hello, Bob!

Function Overloads:

Function overloads allow you to define multiple type signatures for a function, ensuring it can handle different argument types.


function getLength(input: string): number;
function getLength(input: any[]): number;
function getLength(input: any): number {
  if (typeof input === "string") {
    return input.length;
  } else if (Array.isArray(input)) {
    return input.length;
  } else {
    return 0;
console.log(getLength("Hello")); // Output: 5
console.log(getLength([1, 2, 3])); // Output: 3
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
Accept cookies & close this