Skip to main content

10+ Complex typeScript type defining Tips for Development

 


let's take a look at how you can build complex types in TypeScript using examples of JSON-like structures.

const fullName: { firstName: string; lastName: string } = {
  firstName: 'Lakshmanan',
  lastName: 'Arumugam'
};

console.log(fullName.firstName)
// Output Lakshmanan
enum Weekend {
  Friday = 5,
  Saturday,
  Sunday
};

// Assign a valid value of Weekend
const today: Weekend = 7;  // No bug
console.log(`Today is the ${today}th day of the week!`);
// Output: "Today is the 7th day of the week!"
const threeWords: [ string, number, string] = ['Won', 5, 'games'];

// Calling .concat() on a tuple returns an array
let moreWords = threeWords.concat(['last', 'night']);

// An array is expandable
moreWords[5] = ('!');

console.log(moreWords);
// Output: ["Won", 5, "games", "last", "night", "!"]
const marks: number[] = [ 100, 500, 300, 200, 400 ]

console.log("mark value", marks[0])

// Output: 100
// zipcodes is an array of strings
let zipcodes: Array<string> = ['03255', '02134', '08002', '03063'];

// Pushing a number to zipcodes will generate an error
// Error: Argument of type 'number' is not assignable to parameter of type 'string'.
zipcodes.push(05115);
interface StatusObject {
    id: number;
    name: string;
}

interface Status {
    [key: string]: StatusObject
}

const statusValues: Status = {
    "0": { "id": 0, "name": "Available" },
    "1": { "id": 1, "name": "Ready" },
    "2": { "id": 2, "name": "Started" }
 };

 console.log(statusValues["0"].name)
//  Output: "Available"

interface Color {
    color: string;
    value: string;
}

const colors:Color[] = [
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    }
]

console.log(colors[0].color)
// Output: "red"
interface Bakery {
    id:      string;
    type:    string;
    name:    string;
    ppu:     number;
    batters: Batters;
    topping: Topping[];
}

interface Batters {
    batter: Topping[];
}

interface Topping {
    id:   string;
    type: string;
}


const bakery: Bakery =  {
  "id": "0001",
  "type": "donut",
  "name": "Cake",
  "ppu": 0.55,
  "batters": {
    "batter": [
      {
        "id": "1001",
        "type": "Regular"
      }
    ]
  },
  "topping": [
    {
      "id": "5001",
      "type": "None"
    }
  ]
}

console.log(bakery.batters.batter[0].id)
// Output: "1001"
interface Car {
  make: string;
  model: string;
  mileage?: number;
}

let FordCard: Required<Car> = {
  make: 'Ford',
  model: 'Focus',
  mileage: 12000 // `Required` forces mileage to be defined
};

let KiaCard: Required<Car> = {
  make: 'Ford',
  model: 'Focus'
};

//Error
//Property 'mileage' is missing in type '{ make: string; model: string; }' but required in type 'Required<Car>'.
interface Brand {
  brand: string;
}

interface Model extends Brand {
  model: string;
}

class Car implements Model {
  brand;
  model;
  constructor(brand: string, model: string) {
    this.brand = brand;
    this.model = model;
  }
  log() {
    console.log(`Drive a ${this.brand} ${this.model} today!`);
  }
}

const myCar: Car = new Car('Nissan', 'Sentra'); 
myCar.log();

// Output: "Drive a Nissan Sentra today!"
// Define types for product and customer
type Product = {
  id: number;
  name: string;
  price: number;
  stock: number;
};

type Customer = {
  id: number;
  name: string;
  email: string;
};

// Define types for order and order status
type OrderStatus = "pending" | "processing" | "shipped" | "delivered" | "cancelled";

type Order = {
  id: number;
  customer: Customer;
  products: { product: Product; quantity: number }[];
  status: OrderStatus;
};

// Define type for the inventory management system
type InventorySystem = {
  products: Product[];
  customers: Customer[];
  orders: Order[];
  addProduct: (product: Product) => void;
  addCustomer: (customer: Customer) => void;
  placeOrder: (order: Order) => void;
};

// Create an instance of the inventory management system
const inventory: InventorySystem = {
  products: [],
  customers: [],
  orders: [],
  addProduct(product) {
    this.products.push(product);
  },
  addCustomer(customer) {
    this.customers.push(customer);
  },
  placeOrder(order) {
    // Check if products are in stock before placing the order
    for (const { product, quantity } of order.products) {
      const availableProduct = this.products.find(p => p.id === product.id);
      if (!availableProduct || availableProduct.stock < quantity) {
        throw new Error(`Product ${product.name} is out of stock.`);
      }
    }

    // Deduct ordered quantities from the product stock
    for (const { product, quantity } of order.products) {
      const availableProduct = this.products.find(p => p.id === product.id);
      if (availableProduct) {
        availableProduct.stock -= quantity;
      }
    }

    this.orders.push(order);
  },
};

// Example usage
const newProduct: Product = { id: 1, name: "Widget", price: 10, stock: 100 };
inventory.addProduct(newProduct);

const newCustomer: Customer = { id: 1, name: "Alice", email: "alice@example.com" };
inventory.addCustomer(newCustomer);

const newOrder: Order = {
  id: 1,
  customer: newCustomer,
  products: [{ product: newProduct, quantity: 3 }],
  status: "pending",
};
inventory.placeOrder(newOrder);

console.log(inventory);
// Output: 
// {
//   "products": [
//     {
//       "id": 1,
//       "name": "Widget",
//       "price": 10,
//       "stock": 97
//     }
//   ],
//   "customers": [
//     {
//       "id": 1,
//       "name": "Alice",
//       "email": "alice@example.com"
//     }
//   ],
//   "orders": [
//     {
//       "id": 1,
//       "customer": {
//         "id": 1,
//         "name": "Alice",
//         "email": "alice@example.com"
//       },
//       "products": [
//         {
//           "product": {
//             "id": 1,
//             "name": "Widget",
//             "price": 10,
//             "stock": 97
//           },
//           "quantity": 3
//         }
//       ],
//       "status": "pending"
//     }
//   ]
// }

This example demonstrates how TypeScript's advanced typing features can be used to ensure type safety and structure in a complex application scenario.

For more examples check out my blogs

Comments

Popular posts from this blog

Advanced Next.js URL handling with URLSearchParams

  Video Tutorial Introduction In Next.js, you can work with URL query parameters using the next/router module, which provides a way to access and manipulate the query string parameters of the current URL. Query parameters are typically used to pass data from one page to another or to filter content on a page. Here's how you can work with URL query parameters in Next.js: Step 1: Setup next.js project. if you want more about it  read the article Step 2: Import URL search params in your file  page.tsx|jsx . import { useSearchParams } from 'next/navigation' Step 3: Use the useSearchParams hook into the file like below: export default function Example() { const searchParams = useSearchParams()!; } Step 4: Accessing query params value into your component: export default function Example() { let term; const searchParams = useSearchParams()!; // Set updated value to the term if(searchParams?.has('term')) { term = searchParams.get('term'); } retur...

Tailwind CSS theming system detected theme, manual mode dark and light theme with NextJS

Introduction?   In the ever-evolving world of web development, user experience plays a crucial role in determining the success of a website or web application. One aspect of user experience that has gained significant attention in recent years is the choice between light and dark themes. Users prefer different themes based on their surroundings and personal preferences, and as a developer, you can enhance their experience by offering theme options that adapt to their needs. In this guide, we'll explore how to implement system preferences, light and dark themes in a Next.js application with the help of Tailwind CSS. Why Implement System Preferences and Theme Switching? The choice between light and dark themes is not just about aesthetics; it also impacts usability and accessibility. Users often prefer a dark theme in low-light environments, while a light theme is preferred during the day. To provide a seamless user experience, you can implement system preferences to detect the user...

Building Cross-Platform PWAs with Next.js: From Web to Mobile

A Progressive Web App (PWA) is a type of web application that offers a user experience similar to that of a traditional native mobile app or desktop application. PWAs are designed to be fast, reliable, and engaging, and they combine the best features of web and mobile apps. Here are some key characteristics and features of PWAs: Progressive Enhancement:  PWAs are designed to work on any platform, whether it's a desktop, mobile device, or tablet. They provide a consistent user experience across various screen sizes and resolutions. Offline Capabilities:  One of the defining features of PWAs is their ability to work offline or in low-network conditions. They achieve this through the use of service workers, which cache essential resources and enable the app to function even when there's no internet connection. Responsive Design:  PWAs are built with responsive web design in mind, ensuring that the user interface adapts to different screen sizes and orientations, providing a ...

Step-by-Step Guide to Setting up Next.js with Tailwind CSS

Introduction Web development frameworks and libraries are evolving at a rapid pace, and staying up-to-date with the latest technologies is essential for building modern, responsive web applications. Next.js and Tailwind CSS are two popular tools that have gained significant attention in the web development community. Next.js is a powerful React framework for building server-rendered web applications, while Tailwind CSS is a utility-first CSS framework that simplifies styling and offers a responsive design system. why next.js use over react? Next.js is a framework built on top of React that provides a number of features and benefits that make it a good choice for building modern web applications. Some of the reasons why you might choose to use Next.js over React include: Server-side rendering (SSR). Next.js provides built-in support for SSR, which can improve the performance and SEO of your application. Static site generation (SSG). Next.js can also generate static HTML pages that can...

No code API development for front end engineer/web developer

  Creating an API without writing any code might seem impossible, but there are ways to streamline the process and simplify development using low-code or no-code tools. In this blog post, we will explore various approaches to develop APIs without extensive coding. Code demo URL Thanks for reading!