↓ Ir para o conteúdo principal

← todas as notas

📎 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 single number, then is changed to string to show the basic type-checking problem.
  • Using number | string alone 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 | string restricts the generic argument to allowed types.
  • A default type parameter like S = number lets makeState() 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, F and S, for a pair with first and second fields.
  • 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 class State<S> and notes that type parameters are passed when instantiating the class.