All quizzesEasy
Union & Intersection Types — Series 2
Preview — 3 of 10 questions
javascript
interface Profile { social?: { twitter?: string } }
function getTwitter(p: Profile): string | undefined {
return p.social?.twitter;
}
getTwitter({});
getTwitter({ social: {} });ABoth calls throw a runtime error
BBoth calls return undefined safely — ?. short-circuits the whole expression at whichever level is actually missing, whether that's social itself or just twitter within it, without throwing either way
COnly the first call is safe; the second throws, because social exists but twitter doesn't
DCompile-time error — ?. can only appear once per chained expression
javascript
function getPageTitle(title: string | undefined): string {
return title ?? "Untitled";
}
getPageTitle("");
getPageTitle(undefined);AgetPageTitle("") returns "" (the empty string itself, since it's a valid, non-nullish value); getPageTitle(undefined) returns "Untitled"
BBoth calls return "Untitled", because ?? treats an empty string the same way it treats undefined
CBoth calls return "", since ?? never actually triggers here
DCompile-time error — ?? can only be used with a string | null parameter type, not string | undefined
javascript
type EventName = `on${string}`;
const a: EventName = "onClick";
const b: EventName = "click";ABoth a and b compile fine
BBoth are compile-time errors — template literal types can't be used as a variable's type annotation
Cb compiles fine; a is a compile-time error, because "onClick" is too specific to match the pattern
Da compiles fine, because "onClick" matches the pattern on${string} (starts with "on", followed by anything); b is a compile-time error, since "click" doesn't start with "on"
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.