Don’t want to read the text, then directly to see the video: www.bilibili.com/video/BV1sY…

When you first see T in TypeScript generics, does it sound strange?

The T in the figure is called the generic variable, and it is the type placeholder we want to pass to the identity function.

Just like passing parameters, we chain the actual type specified by the user to the parameter type and return value type.

So what does T mean? The generic variable T in the figure represents Type, and in fact T can be replaced by any valid name. In addition to T, common generic variables include K, V, and E.

  • K Key indicates the type of the Key in the object.
  • V Value indicates the type of the Value in the object.
  • E Element indicates the Element type.

Of course you don’t have to define just one type variable, you can introduce any number of type variables. Here we introduce a new type variable U that extends the identity function we defined.

When calling the identity function, we can explicitly specify the actual type of the generic variable. Of course, you can leave out the type of a generic variable and let TypeScript do the type inference for you.

After watching the above animation, do you already understand generic variables? If you understand, feel free to leave a comment in the comments section. If that’s not enough, you can continue to read Bob’s post on TypeScript generics that you didn’t know about.

Finally, do you like to learn TS in this form? If you like it, remember to like and bookmark it.