Generic Basics — Series 3

Preview — 3 of 10 questions

javascript
function identity<T>(value: T): T {
  return value;
}

const a = identity(42);
const b = identity<number>(42);
const c = identity<string>(42);
AAll three compile — an explicit type argument is only a hint
Bc compiles, and 42 is converted to "42"
Cb and c fail — you may never supply a type argument explicitly when it can be inferred
Da and b are number; c is a compile-time error — the explicit argument pins T = string, and 42 isn't a string

javascript
function firstOf<T>(items: T[]): T {
  return items[0];
}

const a = firstOf([1, 2, 3]);
const b = firstOf([1, "two"]);
Aa is number, b is a compile-time error — a generic array argument must be homogeneous
Ba is number, b is string | number — T is inferred as the union of the element types
CBoth are any — arrays with mixed types defeat inference
Da is number[], b is (string | number)[] — T is inferred as the whole array type

What is the type of r?

javascript
function swap<A, B>(pair: [A, B]): [B, A] {
  return [pair[1], pair[0]];
}

const r = swap(["age", 30]);
A[number, string]
B[string, number]
C(string | number)[]
DCompile-time error — a function may declare only one type parameter

Sign up free to play

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