TypeScriptLesson 8 of 16
Generics
A generic is a function or type with a type parameter, usually called T. The same code then works with numbers, strings or objects without losing type checks.
Key points
- function first<T>(items: T[]): T | undefined — T is filled in at the call.
- T is usually inferred: first([10, 20]) returns number | undefined.
- Interfaces can be generic too: Box<boolean>.
- T extends { length: number } is a constraint: only values with a length fit.
Example
function first<T>(items: T[]): T | undefined { return items[0];} const n = first([10, 20]); // number | undefinedconst s = first(["a", "b"]); // string | undefined interface Box<T> { value: T;}const flag: Box<boolean> = { value: true }; function longest<T extends { length: number }>(a: T, b: T): T { return a.length >= b.length ? a : b;}// longest(10, 20); // error: number has no length console.log(`${n} ${s} ${flag.value}`);console.log(longest("tea", "coffee"));console.log(longest([1, 2, 3], [4]).join("-"));first returns exactly the type stored in the array, not any. longest accepts strings and arrays but not numbers, because a number has no length.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Make chunk generic, cut the array into pages with slice and uncomment the second call. Output: "a,b | c,d | e" and "1,2,3 | 4,5,6 | 7".
Output
What your program prints appears here.