FE7: The modern frontend toolkit

Lesson 2 of 5 ยท reading 15โ€“25 minutes; practice and project time is on the module page

TypeScript for components and data

๐ŸŽฏYou'll be able to

Type props and data with TypeScript so mistakes show up before the page runs.

๐Ÿ The everyday picture

A railway reservation form has fixed boxes: a 10-digit PNR, a date, a number of passengers. The clerk can reject a wrong entry before the ticket is printed. TypeScript checks your code's "boxes" before it runs.

๐Ÿ“˜What it really is

type ProductCardProps = {
  product: { id: string; name: string; pricePaise: number; inStock: boolean };
  onAdd: (id: string) => void;
};

๐Ÿ“A worked example

Kirana's API sometimes returned price as a string ("120.00") for older products. In plain JavaScript, price * qty worked by accident, but price + deliveryFee produced "120.0030".

const Product = z.object({
  id: z.string(),
  name: z.string(),
  pricePaise: z.number().int().nonnegative(),
});
type Product = z.infer<typeof Product>;
const products = z.array(Product).parse(await res.json());   // fails loudly on bad data

The schema caught 14 products with string prices on the first run. The backend team fixed them, and the cart bug didn't return.

๐ŸŒWhere it's used

๐Ÿ“Case scenario

A developer silences a TypeScript error with as any to meet a deadline. Two weeks later, orders fail for customers without a saved address: the code reads user.address.pincode, and address can be missing. Removing the any, handling the missing address with a clear prompt, and adding a lint rule against any prevents a repeat.

๐Ÿ–ฑ๏ธTry it

Convert your Kirana product card and cart to TypeScript with strict mode. Add a Zod schema for the product API response, feed it one bad product on purpose, and see where it fails.

โš ๏ธCommon mistakes

๐Ÿ› ๏ธFor your project

Run npx tsc --noEmit in the starter kit; Project 2's checklist asks for zero type errors.

โœ…Quick check

Why validate API data at runtime when you already have TypeScript types?

Show the answer

Types are removed when the code runs, so they can't check what the server actually sends.

What does any do?

Show the answer

It switches off type checking for that value, hiding mistakes.

โ† PreviousWhat build tools do
ProLearners Assist