Welcome back! In this post, we’ll cover some TypeScript basics and create our first component for the Restaurant POS system.
Let’s start with some key TypeScript concepts:
- Static Typing TypeScript’s main advantage is its static typing system. Let’s look at an example:
let tableNumber: number = 5;
let serverName: string = “John Doe”;
let isOccupied: boolean = false;
// This would cause a compile-time error
// tableNumber = "Six"; // Type 'string' is not assignable to type 'number'
- Interfaces Interfaces allow us to define the structure of objects:
interface MenuItem {
id: number;
name: string;
price: number;
category: string;
}
const burger: MenuItem = {
id: 1,
name: "Cheeseburger",
price: 9.99,
category: "Main Course"
};
Now, let’s create our first component: a simple menu item display.
Create a new file src/components/MenuItem.tsx
:
import React from ‘react’;
interface MenuItemProps {
id: number;
name: string;
price: number;
category: string;
}
const MenuItem: React.FC<MenuItemProps> = ({ id, name, price, category }) => {
return (
<div className="menu-item">
<h3>{name}</h3>
<p>Price: ${price.toFixed(2)}</p>
<p>Category: {category}</p>
</div>
);
};
export default MenuItem;
Now, let’s use this component in our App.tsx
:
import React from ‘react’;
import MenuItem from ‘./components/MenuItem’;
const App: React.FC = () => {
const sampleMenuItem = {
id: 1,
name: "Cheeseburger",
price: 9.99,
category: "Main Course"
};
return (
<div className="App">
<h1>Restaurant POS</h1>
<MenuItem {…sampleMenuItem} />
</div>
);
};
export default App;
This example demonstrates how TypeScript helps us ensure that we’re passing the correct props to our components. If we tried to pass an invalid prop or omit a required one, TypeScript would alert us at compile-time.
In our next blog post, we’ll expand on this by creating a menu list component and introduce some more advanced TypeScript concepts like generics and union types.
To wrap up, let’s visualize the component structure we’ve created so far:
This diagram shows our current simple structure, with the App component rendering a MenuItem component. As we progress, we’ll see this structure grow more complex.
Stay tuned for our next post where we’ll dive deeper into TypeScript and expand our POS system’s functionality!
Top comments (0)