All quizzesMedium
Mapped & Conditional Types — Series 3
Preview — 3 of 10 questions
What is config's type, and does the assignment compile?
javascript
const config = { mode: "dark", retries: 3 } as const;
config.retries = 5;A{ mode: string; retries: number } — the assignment compiles
B{ readonly mode: string; readonly retries: number } — the assignment fails
C{ readonly mode: "dark"; readonly retries: 3 } — the assignment fails, because every property is readonly
D{ mode: "dark"; retries: 3 } — the assignment fails because 5 isn't the literal 3
javascript
function describe(value: string | null) {
if (typeof value === "object") {
return value.toFixed(2);
}
return value.toUpperCase();
}ACompile-time error — inside the if, value narrows to null, which has no toFixed
BCompiles fine — typeof value === "object" excludes null, so the branch is unreachable
CCompiles fine, and throws at runtime only when value is null
DCompile-time error on the else path — value is still string | null there
javascript
class HttpError extends Error {
constructor(public status: number) {
super(`HTTP ${status}`);
}
}
function report(e: Error) {
if (e instanceof HttpError) {
return e.status;
}
return e.message;
}ACompile-time error — e is declared Error, so it can never narrow to a subclass
BCompiles fine — instanceof narrows e to HttpError in the branch, and back to Error afterwards
CCompiles fine, but e.status is number | undefined because the check is only a runtime guard
DCompile-time error on e.message — after the if, e is narrowed to Error & not HttpError, which has no members
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.