JS Built-ins
TypeScriptbeginner

Generics β€” swap<T, U>

πŸ“– Usage Example
function swap<T, U>(pair: [T, U]): [U, T] { return [pair[1], pair[0]] }
swap([1, 'hello'])   // β†’ ['hello', 1]

swap<T, U> reverses a two-element tuple, preserving the individual types.

Generics: swap a Pair

Challenge: Implement swap<T, U>(pair: [T, U]): [U, T] that reverses a two-element tuple.

swap([1, 'a'])     // β†’ ['a', 1]
swap([true, 42])   // β†’ [42, true]
πŸ’‘ Hints (1)
  • β€’ Just destructure or index into the tuple.