Skip to content

Lesson 1 of 9 · 20m

Types Are Component Contracts

Stop treating props as syntax and start treating them as an API boundary: what callers may pass, what they must pass, and what combinations are illegal.

The first TypeScript lesson I give React engineers has nothing to do with syntax: your props type is a public API. If the type permits nonsense, someone will eventually pass nonsense — usually at 2 a.m., through a CMS integration you forgot existed.

Type the contract, not the implementation

type UserAvatarProps = {
  user: {
    id: string;
    displayName: string;
    avatarUrl?: string;
  };
  size?: "sm" | "md" | "lg";
};
export function UserAvatar({ user, size = "md" }: UserAvatarProps) {
  return <img className={`avatar avatar-${size}`} src={user.avatarUrl ?? "/img/fallback-avatar.png"} alt="" />;
}

The important part is not size?:; it is the decision that callers need only a narrow user shape. UserAvatar does not demand your entire database User entity. Narrow inputs make components easier to reuse and test because the type says exactly what the component truly depends on.

Prefer inference inside, explicit types at the boundary

Do not annotate every local variable. TypeScript's inference is one of its best features. Annotate component props, function returns that cross module boundaries, and places where inference would become any.

const label = user.displayName.trim() || "Unknown user"; // inferred string
const initials = label.slice(0, 2).toUpperCase();        // inferred string

Make illegal states impossible

A boolean pair is usually a lie:

// bad: all four combinations compile, two are meaningless
type Props = { loading?: boolean; error?: boolean };
// better: exactly the states the UI can represent
type FeedbackProps =
  | { status: "idle" | "loading" }
  | { status: "error"; message: string }
  | { status: "ready" };

When the compiler rejects an impossible combination, that is not friction. That is the type system doing review work before production does it for you.

Field notes

  • Optional props should mean "caller may omit this," not "we were too lazy to decide."
  • Avoid importing giant entity types into leaf components; accept the smallest useful structural shape.
  • If a component accepts callbacks, type the callback parameters precisely — (value: string) => void, not Function.
  • Public component props are worth documenting with comments only when the type cannot express the intent.

Was this lesson helpful?

Sign in to rate