AI Hints
Home›TypeScript Tutorial›Template Types and Practice
TypeScript · Lesson 71 of 120

Practice: Utility Types

An update form.

⏱ 2 min read▶ Video at 54:21🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Let's practise. A bike edit form lets staff change some fields, but never the ID. We'll build its types from the bike type, so they always stay in sync.

Practice: Utility Types
From the video: Practice: Utility Types
  • An edit form
  • Never the id
  • Stay in sync

Types for an edit form

Bike edit omits the ID, then makes the rest partial. Errors maps each editable field to an optional message. Validate fills in errors. Run it. The negative price is caught.

app.tstypescript
type Bike = { id: number; model: string; price: number; stock: number };

type BikeEdit = Partial<Omit<Bike, "id">>;
type Errors = { [K in keyof BikeEdit]?: string };

function validate(edit: BikeEdit): Errors {
  const errors: Errors = {};
  if (edit.price !== undefined && edit.price <= 0) errors.price = "Price must be positive";
  if (edit.model !== undefined && edit.model.trim() === "") errors.model = "Model is required";
  return errors;
}

console.log(validate({ price: -10 }));
console.log(validate({ model: "Trail 600" }));
Output
{ price: 'Price must be positive' }
{}

Summary

Combining Omit, Partial, and mapped types keeps form types in sync with the data. Next, the advanced types quiz.

Key takeaways
  • Partial<Omit<...>>
  • Mapped errors
  • In sync
Next up: Advanced Types Quiz — test yourself