TypeScript Functions


Understanding Functions in TypeScript

In TypeScript, functions are more than just reusable blocks—they let you define what goes in and what comes out using types. This brings clarity and safety to your code.


Defining Return Type

You can clearly mention what kind of result your function will return:

function currentTimestamp(): number {   
   return Date.now(); 
} 

The : number means this function returns a number.

If you don’t explicitly write the return type, TypeScript will figure it out based on the return value.


Void Return

Use void when your function doesn't send anything back:

function greetUser(): void {   
   console.log("Welcome!"); 
} 

This tells TypeScript: “No need to expect a return value.”


Function Parameters with Types

Each argument passed into a function can also be typed:

Without a type, it defaults to any, which is not safe.


Optional Parameters

Want to make a parameter non-mandatory? Add a ?:

function calculateTotal(price: number, tax?: number) {   
  return price + (tax || 0);
 } 

Here, tax is optional — if it’s not given, it won’t break the function.


Default Parameter Values

You can assign a default value to a parameter, so it uses that if nothing is passed:

function raiseToPower(base: number, exp: number = 2) {   
   return base ** exp; 
} 

If exp isn't provided, it uses 2.


Named Parameters with Types

You can destructure object inputs and type their properties:

function divideValues({ num, den }: { num: number; den: number }) {   
   return num / den; 
} 

Useful when you want clear, readable inputs.


Rest Parameters

You can accept a flexible number of arguments using the rest syntax (...). TypeScript expects these to be an array: ts Copy Edit

function totalSum(first: number, second: number, ...others: number[]) {   
   return first + second + others.reduce((sum, val) => sum + val, 0); 
} 

Type Aliases for Functions

You can predefine a function’s shape using a custom name:

type Formatter = (text: string) => string;  

Const toUpperCase: Formatter = (text) => text.toUpperCase(); 

This is helpful for consistency across your codebase.


Prefer Learning by Watching?

Watch these YouTube tutorials to understand TYPESCRIPT Tutorial visually:

What You'll Learn:
  • 📌 Typescript tutorial for beginners #10 function
  • 📌 TypeScript Crash Course #6 - Functions
Previous Next