TypeScript Intermediate — Series 2

Preview — 3 of 10 questions

javascript
const enum Status {
  Active,
  Inactive,
}
let s = Status.Active;
Aconst enum members can't be accessed at all outside the file where they're declared
Bconst enum is inlined at compile time — the emitted JavaScript replaces Status.Active with its literal value 0, and no Status object exists at runtime
Cconst enum requires every member to have an explicit value
Dconst enum behaves exactly like a regular enum — const is purely cosmetic and has no compilation effect

javascript
class Dog { bark() { return "Woof"; } }
class Cat { meow() { return "Meow"; } }
function speak(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    return animal.bark();
  }
  return animal.meow();
}
ACompile-time error on animal.bark() — animal is still typed Dog | Cat inside the if block
BCompile-time error on animal.meow() — Dog was already checked first
CCompiles fine — instanceof Dog narrows animal to Dog inside the if branch, and to Cat in the remaining branch, so both method calls type-check without any assertion
DCompiles fine, but only after adding an explicit as Dog / as Cat assertion

javascript
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function area(shape: Shape): number {
  if (shape.kind === "circle") {
    return Math.PI * shape.radius ** 2;
  }
  return shape.side ** 2;
}
AComparing the shared literal kind field narrows shape to the specific union member whose kind matches — TypeScript uses kind as a discriminant to know which shape it's dealing with
Bradius and side are treated as optional properties present on every member of the union
CTypeScript widens shape to any inside conditional branches, so any property access is allowed
DThis is a compile-time error — shape.radius isn't accessible without an explicit type assertion

Sign up free to play

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