Generics basics
Click her to play with interface codes
If you use one of the programming languages like Java, Typescript, Swift or similar OOP languages then you know having generics capability is very helpful in a large project.
I’ll play with Typescript example that it is used in Angular framework, consider the following function, license ().
The license function is responsible to return the argument passed in. It is obvious that string type is assigned to both argument and return type, but this function is not expandable or generic! I can replace the string to typescript ‘any’, however, the ability to define which type should I expect to return then it is lost. Good news, using generics will resolve the issue and look at the function license again.
I added ‘<T>’ after the name of the function license, the angled brackets ‘< >’ with type variable ‘T’ are turning the typescript license function to a generic function. The ‘type variable’ is known as a ‘type parameter’ and generic parameter. I can use any name but I am following the typescript convention by using ‘T’.
I’ll add another type to license function and it works fine and it is still arg0 is the return parameter.
Oh, how about if I wanted to return an object with the two types? Yes of course, here I’ll use ‘tuple’ to do the job. The tuple should be familiar to typescript and swift programming languages and it is very useful. This is the change on my generic function license for returning two objects. Cool
The license function is now capable to return a ‘tuple’ containing a ‘T’ and ’V’ arguments. Well, there is another way to return more than one object with generics. That is using the ‘interface’ to return the types. OK, I’ll create a generic license interface, like this:
The above interface can be used as the return type of license() and fulfill the requirement. This way it is more readable for larger scale programs.
The license() function is passing types ‘T’ and ‘V’ into the function and License interface which provides the return types in reference to the argument types. That is cool.
There is also generic class. The typescript generic class ensures the data types are used consistently within the class objects. The class generic syntax is similar to what I have shown here, so here is a quick sample:
The generic classes works on instance side and static members are not using the class generic type parameter.
That is it for a quick introduction to typescript generics. for more info: typescript