Back to questionsWhich type does TypeScript infer for
JuniorTheoryCommon
Which type does TypeScript infer for shown?
function label(city: string | null) {
const shown = city ?? "—";
return shown;
}
console.log(label(null));string
- Expecting
string | null:??replacesnullandundefinedwith its right side, and the compiler follows it, sonulldrops out of the type. - Expecting the literal type
"—"because ofconst:shownmay hold any string fromcity, andstring | "—"is the same asstring.
- What type does
city?.toUpperCase()have in this function, and why? - How does
city ?? "—"differ fromcity || "—"whencityis an empty string?