Good Code
The good version separates an omitted draft field from a present field that explicitly has no avatar.
Lesson 07
Use optional and nullable fields to describe different kinds of absence.
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;
}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";
}The good version separates an omitted draft field from a present field that explicitly has no avatar.
The bad version allows both undefined and null everywhere, so callers cannot tell whether data was missing, intentionally cleared, or simply not loaded yet.