AI Hints
Home›TypeScript Tutorial›Utility Types
TypeScript · Lesson 64 of 120

Partial and Required

Optional or not.

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

TypeScript comes with ready made utility types. Partial makes every property optional. Required makes every property required. They're perfect for updates.

Partial and Required
From the video: Partial and Required
  • Built-in utilities
  • Partial
  • Required

Partial updates

Update bike takes a bike, and a partial bike with only the changes. Spreading merges them. We change just the price. Run it.

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

function updateBike(bike: Bike, changes: Partial<Bike>): Bike {
  return { ...bike, ...changes };
}

const trail: Bike = { model: "Trail 500", price: 849.5, stock: 12 };
console.log(updateBike(trail, { price: 799 }));
Output
{ model: 'Trail 500', price: 799, stock: 12 }

Required

Settings has an optional currency. Required of settings removes every question mark, so leaving it out is now an error. Run it.

app.tstypescript
type Settings = { currency?: string; freeFrom?: number };

const full: Required<Settings> = { freeFrom: 50 };
Output
app.ts line 3: Property 'currency' is missing in type '{ freeFrom: number; }' but required in type 'Required<Settings>'.

Summary

Partial makes everything optional, Required makes everything required. Next, Pick and Omit.

Key takeaways
  • Partial<T>
  • Required<T>
  • Updates
Next up: Pick and Omit — choose properties