Syncing account progress…

Back

Beginner · 10 min

Project: a typed order summary

Combine object types, arrays, functions, and runtime validation in a small project.

Model the order

Describe each item once and reuse that type in the collection and the calculation. Types check the shape; validation still checks business rules such as a positive quantity.

type Item = { name: string; price: number; quantity: number };
function lineTotal(item: Item): number { return item.price * item.quantity; }
console.log(lineTotal({ name: "Notebook", price: 4, quantity: 3 }));

Output

12

Check a business rule

A number annotation permits negative numbers too. Put value checks in executable code when the application needs a narrower rule.

function validQuantity(value: number): boolean {
  return value > 0 && value % 1 === 0;
}
console.log(validQuantity(2.5));

Output

false

Put it into practice

  1. Read the types and predict the output before running the examples.
  2. Complete the task, then check your understanding with the practice questions.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Finish the order summary

Make "lineTotal" multiply the price by the quantity. Keep the "Item" type and number return annotation. Display "Total: 16.00".

Practice