krishankant singhal
3 min readOct 1, 2024

--

Blog Post 3: Advanced TypeScript Concepts and Building a Menu List

Welcome back, developers! In our last post, we created a simple MenuItem component. Today, we’ll expand our application by implementing a MenuList component and dive into some more advanced TypeScript concepts.

Let’s start by introducing generics and union types, two powerful features of TypeScript that will help us write more flexible and type-safe code.

  1. Generics
    Generics allow us to create reusable components that can work with different types. Let’s create a generic List component:

import React from ‘react’;
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
function List<T>({ items, renderItem }: ListProps<T>) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{renderItem(item)}</li>
))}
</ul>
);
}
export default List;

This List component can work with any type of item, making it very flexible.

2. Union Types
Union types allow a value to be one of several types. Let’s use this to create a more flexible price property for our MenuItem:


type Price = number | { amount: number; currency: string };
interface MenuItem {
id: number;
name: string;
price: Price;
category: string;
}

Now, let’s update our MenuItem component to handle this new Price type:


import React from ‘react’;
type Price = number | { amount: number; currency: string };
interface MenuItemProps {
id: number;
name…

--

--

krishankant singhal
krishankant singhal

Written by krishankant singhal

Angular,Vuejs,Android,Java,Git developer. i am nerd who want to learn new technologies, goes in depth.

No responses yet