Mapped & Conditional Types — Series 2

Preview — 3 of 10 questions

javascript
function describe(value: string | null): string {
  const safe = value ?? "N/A";
  return safe.toUpperCase();
}
A?? narrows value itself in place, so value becomes string starting from this line
B?? produces a value (safe) whose type combines the non-nullish members of value's type with the fallback's type — here, string (from string | null minus null) unioned with the fallback's string, giving plain string
CTypeScript treats ?? as a hidden type assertion, silently casting the result to string
Dsafe is typed string | null, but .toUpperCase() happens to also exist on null

javascript
function assertIsString(val: unknown): asserts val is string {
  if (typeof val !== "string") {
    throw new Error("Not a string");
  }
}
function process(val: unknown) {
  assertIsString(val);
  console.log(val.toUpperCase());
}
ACompile-time error — val.toUpperCase() still isn't valid, because val's declared parameter type is unknown
BassertIsString has no effect on val's type inside process — a manual type guard (if (typeof val === 'string')) would still be required
CAfter the call to assertIsString(val) returns, TypeScript narrows val to string for the rest of process — the asserts val is string return type tells the compiler that if the function returns normally (without throwing), val must be a string
DThis narrowing only works if assertIsString is called from directly inside an if statement

javascript
function total(input: number | number[]): number {
  if (Array.isArray(input)) {
    return input.reduce((a, b) => a + b, 0);
  }
  return input;
}
AArray.isArray is a recognized narrowing check — inside the if block, input is narrowed to number[], making .reduce valid without any assertion
BCompile-time error — Array.isArray isn't understood by TypeScript's control-flow narrowing
Cinput remains number | number[] inside the if block, so an explicit as number[] assertion is required before calling .reduce
DArray.isArray only narrows values typed unknown, not a union like number | number[]

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.