Typescript Foundations / Functions

Arrow functions with type

βœ… Basic Syntax with Types

const functionName = (param1: Type1, param2: Type2): ReturnType => {
  // function body
};

✍ Example 1: Adding two numbers

const add = (a: number, b: number): number => {
  return a + b;
};

✍ Example 2: Greeting function

const greet = (name: string): string => {
  return `Hello, ${name}`;
};

πŸ” Implicit vs Explicit Return Types

Implicit:

const double = (x: number) => x * 2; // TypeScript infers return type as number

Explicit:

const double = (x: number): number => x * 2; // Explicitly declares return type

βœ… Best Practice: Explicit return types are safer and clearer for exported/public APIs.


🧠 Arrow Function Returning Object

You must wrap the object in () to avoid confusion with the function body:

const getUser = (id: number): { id: number; name: string } => ({
  id,
  name: "User" + id
});

✨ With Function Type Aliases

type GreetFunction = (name: string) => string;

const greet: GreetFunction = (name) => `Hi, ${name}`;

βœ… Summary

Use

Syntax

Parameters with types

(x: number, y: number)

Return type annotation

: number

Optional param

age?: number

Default param

name: string = "Guest"

Object return

=> ({ id: 1 })

Function type alias

type Fn = (x: number) => number


πŸ§ͺ Real-World Example