Skip to main content

Command Palette

Search for a command to run...

3) Typescript Functions

Updated
View as Markdown
  1. Function Typing in TypeScript
    i) Basic Function Typing

    function add(a: number, b: number): number {
      return a + b;
    }
    
    console.log(add(10, 20));
    

    ii) Arrow Function Typing

    const multiply = (a: number, b: number): number => {
      return a * b;
    };
    

    iii) Function Type Alias

    type MathOperation = (x: number, y: number) => number;
    
    const subtract: MathOperation = (x, y) => {
      return x - y;
    };
    
  2. Optional Parameters
    Optional parameters are marked using ?.

    function greet(name?: string): string {
      return `Hello ${name || "Guest"}`;
    }
    
    console.log(greet());
    console.log(greet("Rahul"));
    

    React Example

    type UserProps = {
      name?: string;
    };
    
    const UserCard = ({ name }: UserProps) => {
      return <h1>Welcome {name || "Guest"}</h1>;
    };
    
  3. Default Parameters
    Default parameters provide fallback values.

    function greet(name: string = "Guest"): string {
      return `Hello ${name}`;
    }
    
    console.log(greet());
    console.log(greet("Rahul"));
    

    React Example

    type HeaderProps = {
      title?: string;
    };
    
    const Header = ({ title = "Dashboard" }: HeaderProps) => {
      return <h1>{title}</h1>;
    };
    
  4. Rest Parameters
    Rest parameters allow multiple arguments.

    function sum(...numbers: number[]): number {
      return numbers.reduce((acc, num) => acc + num, 0);
    }
    
    console.log(sum(1, 2, 3, 4));
    

    React Example

    type TagsProps = {
      title: string;
      tags: string[];
    };
    
    const Tags = ({ title, tags }: TagsProps) => {
      return (
        <div>
          <h2>{title}</h2>
    
          {tags.map((tag, index) => (
            <span key={index}>{tag}</span>
          ))}
        </div>
      );
    };
    
  5. Object Typing in TypeScript
    Object typing ensures objects follow a structure.
    i) Basic Object Typing

    type User = {
      id: number;
      name: string;
      isAdmin: boolean;
    };
    
    const user: User = {
      id: 1,
      name: "Rahul",
      isAdmin: true,
    };
    

    ii) Nested Object Typing

    type Address = {
      city: string;
      country: string;
    };
    
    type Employee = {
      id: number;
      name: string;
      address: Address;
    };
    
    const emp: Employee = {
      id: 101,
      name: "John",
      address: {
        city: "Pune",
        country: "India",
      },
    };
    

    React Object Typing Example

    type ProfileProps = {
      user: {
        id: number;
        name: string;
        email: string;
      };
    };
    
    const Profile = ({ user }: ProfileProps) => {
      return (
        <div>
          <h2>{user.name}</h2>
          <p>{user.email}</p>
        </div>
      );
    };