Type System Basics — Series 2

Preview — 3 of 10 questions

javascript
const add: (a: number, b: number) => number = (a, b) => a + b;
add("1", "2");
ACompiles fine — the type annotation only constrains the declaration, not how the function is later called
BCompile-time error — add's type requires two number arguments, so passing strings is rejected
CCompiles fine, since the arrow function (a, b) => a + b has no explicit parameter type annotations of its own
DRuntime error: cannot add two strings

javascript
type Pair = [string, number];
const p: Pair = ["age", 30];
const [label, amount] = p;
ABoth label and amount are typed any, since tuples don't support destructuring
BThis is invalid syntax — a tuple can only be indexed with [], never destructured
Clabel is typed string and amount is typed number — destructuring a tuple preserves each position's specific type
DBoth label and amount are typed string | number

javascript
enum Level {
  Low,
  Medium,
  High,
}
console.log(Level.Medium);
console.log(Level[1]);
A1 then "Medium" — numeric enums auto-increment from 0, and also support a reverse lookup from the numeric value back to the member's name
B"Medium" then 1
C1 then undefined — numeric enums don't support reverse lookup by index
DThis is a compile-time error — Level[1] isn't valid syntax for accessing an enum member

Sign up free to play

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