Skip to content

Latest commit

 

History

History
63 lines (41 loc) · 2.98 KB

article-1-en.md

File metadata and controls

63 lines (41 loc) · 2.98 KB

What Are K, T, and V in TypeScript Generics?

1

Welcome to the Mastering TypeScript series. This series will introduce the core knowledge and techniques of TypeScript in the form of animations. Let’s learn together! Previous articles are as follows:

简体中文

Does it sound strange when you first see the T in TypeScript generics?

The T in the figure is called a generic type parameter, and it is the type placeholder we wish to pass to the identity function.

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

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

  • K(Key): represents the type of key in the object
  • V(Value): represents the type of value in the object
  • E(Element): represents the element type

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

When calling the identity function, we can explicitly specify the actual type of the generic parameter. Of course, you can also not specify the type of the generic parameter, and let TypeScript automatically complete the type inference for us.

After watching the above animation, do you already understand generic type parameters?

If you like to learn TypeScript in the form of animation, you can follow me on Medium or Twitter to read more about TS and JS!