TypeScript Functions

TypeScript tutorial

🔧 TypeScript Functions

In TypeScript Functions are similar to JavaScript functions, but with type safety.

You can define types for parameters, return values, and even the function itself.

1️⃣ Basic Function

function add(a: number, b: number): number {
return a + b;
}
  • a: number, b: number → parameter types

  • : number → return type

2️⃣ Function with No Return (void)

function greet(name: string): void {
console.log("Hello " + name);
}

3️⃣ Optional Parameters (?)

Optional parameters must come after required ones.

function printName(firstName: string, lastName?: string) {
console.log(firstName, lastName ?? "");
}
printName(“Sanjit”);
printName(“Sanjit”, “Sinha”);

4️⃣ Default Parameters

function multiply(a: number, b: number = 2): number {
return a * b;
}
multiply(5); // 10
multiply(5, 3); // 15

5️⃣ Arrow Functions

Arrow functions with types:

const subtract = (a: number, b: number): number => {
return a - b;
};

Short form:

const square = (x: number): number => x * x;

6️⃣ Function Type Expressions

Define a function’s shape.

type Operation = (x: number, y: number) => number;

const addNumbers: Operation = (a, b) => a + b;

7️⃣ Functions with Union Types

function printId(id: number | string): void {
console.log(id);
}

With narrowing:

function formatValue(value: number | string) {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}

8️⃣ Rest Parameters

Accept multiple arguments.

function sumAll(...numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
sumAll(1, 2, 3, 4);

9️⃣ Function Overloading

Multiple function signatures for one implementation.

function combine(a: number, b: number): number;
function combine(a: string, b: string): string;
function combine(a: any, b: any) {
return a + b;
}
combine(1, 2);
combine(“Hello “, “World”);

🔟 never Return Type

Used when function never returns.

function throwError(msg: string): never {
throw new Error(msg);
}

🔑 Functions Summary

FeatureExample
Basicfunction fn(a: type): type
Void(): void
Optionalparam?: type
Defaultparam = value
Arrow(a: type) => type
Rest...args: type[]
OverloadMultiple signatures
Never(): never

⭐ Best Practices

✔ Always type function parameters
✔ Explicitly type public function returns
✔ Use arrow functions for callbacks
✔ Avoid any in functions

You may also like...