All quizzesEasy
Union & Intersection Types — Series 3
Preview — 3 of 10 questions
javascript
interface Form {
email: string;
phone?: string;
}
type Draft = Partial<Form>;
const d: Draft = {};ACompile-time error — Partial cannot be applied to a type that already has optional properties
BCompiles fine — Draft is { email?: string; phone?: string }, so the empty object is valid
CCompiles fine, but Draft is { email?: string; phone: string } — Partial toggles each modifier
DCompile-time error — email is still required, because Partial only affects the last property
javascript
const mutable: string[] = ["a", "b"];
const ro: readonly string[] = mutable;
const back: string[] = ro;ABoth compile — readonly is erased, so the two types are identical
BBoth fail — a mutable array and a readonly array are unrelated types
Cro fails; back compiles
Dro compiles; back is a compile-time error — a readonly string[] is missing the mutating methods that string[] requires
javascript
function total(input: number | number[]): number {
if (typeof input === "number") {
return input;
}
return input.reduce((a, b) => a + b, 0);
}ACompiles fine — typeof input === "number" narrows to number in the branch, and to number[] after it
BCompile-time error — typeof reports "object" for arrays, so the union is never narrowed
CCompile-time error on input.reduce — input is still number | number[] after the if
DCompiles, but input.reduce is typed any because the array's element type is unknown
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.