Course contentsShow
← React
Lesson 246 of 2,3967. Props FundamentalsFree lesson

TypeScript and Prop Destructuring

Type destructured props correctly in TypeScript, including optional props and default values in the interface.

TypeScript and Prop Destructuring

What you'll learn: How to add TypeScript type annotations when destructuring props, including handling optional props and default values.

When you destructure props in TypeScript, you need to tell TypeScript what shape those props have. This means defining an interface (or type) that describes each prop's type, then using it where you destructure.

Basic Typed Destructuring

Instead of just destructuring like function Button({ label, onClick }), you add a type annotation:

interface ButtonProps {
  label: string;
  onClick: () => void;
}

function Button({ label, onClick }: ButtonProps) {
  return <button onClick={onClick}>{label}</button>;
}

The : ButtonProps tells TypeScript what types label and onClick should be.

Optional Props and Default Values

For optional props, add a ? in the interface and optionally provide a default value in the destructuring:

interface CardProps {
  title: string;
  subtitle?: string;
  isHighlighted?: boolean;
}

function Card({ title, subtitle, isHighlighted = false }: CardProps) {
  // subtitle might be undefined
  // isHighlighted defaults to false if not provided
}

The ? makes subtitle and isHighlighted optional. The = false provides a fallback value during destructuring.

Why Both Interface and Default?

The interface documents what can be passed. The default value determines what happens when it's not passed. TypeScript uses the interface for type checking; React uses the default at runtime.

Key Takeaway: When destructuring props in TypeScript, define an interface describing all props (with ? for optional ones), then annotate the destructured parameters with : InterfaceName. Default values in destructuring provide runtime fallbacks, while the interface provides compile-time type safety.