- 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;
TypeScript Functions
Typed parameters, return types and optional parameters.
✍️ 3 exercises + code challenge in this lessonKey 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
TypeScriptfunction 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));
6 Salam, Mr. Khan 42
TypeScript Functions Practice Exercises
Check what you learned in “TypeScript Functions”.
Declare the return type.
function add(a: number, b: number) { return a + b; }
How do you mark a parameter as optional?
Write greet(name: string, greeting = "Hello") returning "greeting, name!" and log greet("Usman").
Free sign-in required · Google login available
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