Skip to content
dreamcode
dreamcode
Map
Generics
Lesson 13 of 26
+15 XP on finish
TYPESCRIPTChapter 3 · TS Advanced

Reusable code with generics

Generics let a function work over many types while keeping the link between input and output. <T> is a type variable filled in when the function is called.

Worked example

How it reads

  • <T> is a type placeholder bound when the function is called
  • first(items: T[]): T returns the same type the array holds
Cloud tip: You rarely need to pass <string> explicitly; TypeScript infers T from the argument you give.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Write a generic pair<A, B>(a: A, b: B): [A, B] and log pair("Vega", 0.03): [ 'Vega', 0.03 ].

Press Run to check your work.