typescriptnaming-conventionstypescript-genericsidentifier

Why do we use the letters T, U in TypeScript Generics


I noticed most tutorials/courses/articles use T, U... as the name of generic types. Why exactly, why not assign normal names instead?


Solution

  • It's just a convention; different kinds of things have visibly different name formats so you can tell what kind of thing something is from what format its name is written in. For example, in Java, Javascript and Typescript it's conventional to use camelCase for variables and method names, UpperCamelCase for class names, and UPPER_SNAKE_CASE for constants; and it's conventional to use T for a type parameter.

    This way, if you see a type named T you know it is a type parameter, whereas if you see a type named Person you know it's not. And if you see person you know it's not a type. Being able to tell apart a class from a type parameter is useful because of type erasure; classes exist at runtime but type parameters are removed from the code during compilation. (This applies moreso in Java than in Typescript, because in Java only type parameters are erased, whereas in Typescript interfaces and type aliases are also erased. But the convention comes from Java and similar languages, so it has stuck.)

    Most likely, the default letter to use is T because it stands for "Type", then just like in mathematics it's conventional to use consecutive letters for multiple variables representing the same kinds of thing, so S, T, U, V are common. Also, K is often used for a generic key type and V for a value type associated with it; in some cases E is used for the type of "elements" in a collection.