Skip to contentPedro Farbo
Lesson 4 / 525 min

Typed Functions

Typed Functions

TypeScript allows you to type parameters, return values, and even the function type itself. This makes your code safer and better documented.

Typing Parameters

typescript
function greeting(name: string): void {  console.log(`Hello, ${name}!`);} greeting("Pedro"); // OKgreeting(42);      // Error: Argument of type 'number'...

Typing Return Values

typescript
function add(a: number, b: number): number {  return a + b;} function isEven(n: number): boolean {  return n % 2 === 0;} // TypeScript infers, but being explicit is a good practicefunction multiply(a: number, b: number) {  return a * b; // return type inferred as number}

Optional Parameters

Use ? for optional parameters (must come last):

typescript
function createUser(  name: string,  email: string,  age?: number): object {  return { name, email, age };} createUser("Pedro", "pedro@email.com");      // OKcreateUser("Pedro", "pedro@email.com", 30);  // OK

Default Parameter Values

typescript
function power(base: number, exponent: number = 2): number {  return Math.pow(base, exponent);} power(5);     // 25 (5²)power(5, 3);  // 125 (5³)

Rest Parameters

To accept a variable number of arguments:

typescript
function sumAll(...numbers: number[]): number {  return numbers.reduce((acc, n) => acc + n, 0);} sumAll(1, 2, 3);       // 6sumAll(1, 2, 3, 4, 5); // 15

Typed Arrow Functions

typescript
// Inlineconst double = (n: number): number => n * 2; // With separate function typetype Operation = (a: number, b: number) => number; const add: Operation = (a, b) => a + b;const subtract: Operation = (a, b) => a - b;

Function Overloads

Define multiple signatures for a function:

typescript
function format(value: string): string;function format(value: number): string;function format(value: string | number): string {  if (typeof value === "string") {    return value.toUpperCase();  }  return value.toFixed(2);} format("hello");  // "HELLO"format(3.14159);  // "3.14"

Functions as Parameters

Pass functions as arguments with typing:

typescript
function execute(  callback: (message: string) => void): void {  callback("Operation completed!");} execute((msg) => console.log(msg)); // Or with a named typetype Callback = (message: string) => void; function executeWithType(callback: Callback): void {  callback("Done!");}

Functions Returning Functions

typescript
function multiplier(factor: number): (n: number) => number {  return (n) => n * factor;} const double = multiplier(2);const triple = multiplier(3); console.log(double(5)); // 10console.log(triple(5)); // 15

This in Functions

Explicitly type this in functions:

typescript
interface User {  name: string;  greet(this: User): void;} const user: User = {  name: "Pedro",  greet() {    console.log(`Hello, I'm ${this.name}`);  }}; user.greet(); // "Hello, I'm Pedro" // Error if we try to call with wrong contextconst greetFn = user.greet;greetFn(); // Error at compile time!

Conclusion

Typed functions make your code more predictable and easier to maintain. In the next lesson, we'll explore generics for creating flexible, reusable components.

Enjoyed the content? Your contribution helps keep everything online and free!

PIX:0737160d-e98f-4a65-8392-5dba70e7ff3e