TypeScript

Lesson 07

Optional properties vs nullable values

Use optional and nullable fields to describe different kinds of absence.

Good Code

profile.ts
type ProfileDraft = {
  displayName?: string;
  avatarUrl: string | null;
};

function renderAvatar(profile: ProfileDraft) {
  // null means avatar is intentionally empty, not merely missing.
  if (profile.avatarUrl === null) {
    return "Use default avatar";
  }

  return profile.avatarUrl;
}

Bad Code

profile.ts
type ProfileDraft = {
  displayName?: string | null;
  avatarUrl?: string | null;
};

function renderAvatar(profile: ProfileDraft) {
  // Mixing optional and null forces callers to guess absence.
  return profile.avatarUrl || "Use default avatar";
}

Review Notes

What to review

Good Code

The good version separates an omitted draft field from a present field that explicitly has no avatar.

Bad Code

The bad version allows both undefined and null everywhere, so callers cannot tell whether data was missing, intentionally cleared, or simply not loaded yet.

Takeaways

  • Use `?` when a property may be omitted and `null` when the property is present but intentionally empty.