As I continue the Udemy course TypeScript: The Complete Developers Guide I’ve been introduced to several new to me concepts. Generics & abstract classes are two tools a developer can use to make their code more reusable and maintainable. More senior developers who are accustomed to strong type languages such as C, Go, Java and Swift are likely already familiar with these concepts.

Generics

As discussed in Typescript Type Declaration when declaring functions the input and output types should be annotated but what if you don’t know what type your input or output will be? Initially it may sound like this is a case that never or rarely happens but has you start to abstract it will come up more often than you might expect. Consider the simple function in Figure 1.

Image for post

Figure 1: Simple pass through function

In the above case the input and output are specified as type any which defeats the whole purpose of TypeScript as it will never find a type error if anything is allowed. Instead we could use generic syntax as denoted by <>to pass in a generic type when the function is called.

Image for post

Figure 2: Simple pass through function with generics

Now the generic type T is passed as a string when it is called in Figure 2. It is noted that you don’t have to name your generic T , it can be named anything much like a variable. Multiple generics can be passed into a function or class as well, for a function passed generics <T, K> would have access to both of them.

#generics #refactoring #typescript #javascript #abstract-class

Generics & Abstract Classes in TypeScript
8.70 GEEK