📎 Webclip
TypeScript Generics for People Who Gave Up on Understanding Generics
The tutorial is aimed at beginner programmers and uses small examples to make TypeScript generics easier to understand. It starts with a makeState() function, then shows how a generic type parameter lets the same function create number-only or string-only states, while extends can restrict allowed types and default type parameters can remove repetitive annotations.
Reading notes#
- The article is written for beginner programmers and is meant as a friendlier alternative to existing TypeScript tutorials.
makeState()first stores a singlenumber, then is changed tostringto show the basic type-checking problem.- Using
number | stringalone does not solve the need for separate number-only and string-only states. makeState<S>()introduces a type parameter so callers can choose the stored type.S extends number | stringrestricts the generic argument to allowed types.- A default type parameter like
S = numberletsmakeState()be called without spelling out<number>every time. - The article compares generic parameters to regular function parameters, but with types instead of values.
makePair()extends the same idea to two type parameters,FandS, for a pair withfirstandsecondfields.- The same pair shape can be extracted into a generic interface or a generic type alias and reused.
- The last section turns
makeState()into a generic classState<S>and notes that type parameters are passed when instantiating the class.
