TypeScript Functions

Typed parameters, return types and optional parameters.

✍️ 3 exercises + code challenge in this lesson
  • Parameter and return types: function add(a: number, b: number): number
  • Optional parameter: title?: string
  • Default value: greeting = "Hello"
  • Rest parameters: ...nums: number[]
  • Function type: type Op = (a: number, b: number) => number;

Key Takeaways: TypeScript Functions

Mastering TypeScript Functions helps you write clean and reliable TypeScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

TypeScript Functions Code Example

TypeScript
function sum(...nums: number[]): number {
  return nums.reduce((a, b) => a + b, 0);
}

function greet(name: string, greeting = "Hello", title?: string): string {
  return `${greeting}, ${title ? title + " " : ""}${name}`;
}

type Op = (a: number, b: number) => number;
const multiply: Op = (a, b) => a * b;

console.log(sum(1, 2, 3));
console.log(greet("Khan", "Salam", "Mr."));
console.log(multiply(6, 7));
Output
6
Salam, Mr. Khan
42
Free sign-in required · Google login available

TypeScript Functions Practice Exercises

Check what you learned in “TypeScript Functions”.

/ 3 solved
Fill in the blank

Declare the return type.

function add(a: number, b: number) { return a + b; }
✓ Correct! Not quite. Try again.
Multiple choice

How do you mark a parameter as optional?

✓ Correct! Not quite. Try again.
Code challenge

Write greet(name: string, greeting = "Hello") returning "greeting, name!" and log greet("Usman").

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services