Use generics like pro
Meet Vaghasiya
Passionate Vue.js & Laravel Developer | JavaScript Lover | Eager to Learn
There is a rule in programming called DRY- don't repeat yourself. generics help us to use this convention in typescript.
let's say there is a function in which we pass the same argument but different types of returns. like string, number, or anything. then we have to make separate functions for all types or we just use type ANY, which is generally worst idea in typescript.
Here we have almost the same code in all functions. we pass the parameter and return the same parameter. which is not a practical example but easy to understand how to use generics. let's understand this.
We define generics in < > . we can say generics are params for types. it acts the same as passing parameters but here we have to pass as type as a parameter. we access these types (line 1) in the triangular brackets with T notation. and tell typescript that args are types of T(which means what we pass as an argument during the calling of function) and return value is also T.
So if we pass <string>, then T means string. so args type is also string and return type is also string. so we can only access string methods on that. otherwise, it will give an error like shown in the screenshot. Also, observe that if we pass <number> then T means number.
We can write anything instead of T. generally we use T because it's typing. but Abc, Xyz anything we can write instead of T.
Pass multiple arguments in generics
we can pass multiple arguments the same as functions.
you can return any type you want from it. like
领英推荐
function makeUser<T, U>(name: T, age: U): [T, U] { // returning tuple [T,U]
? return [name, age];
}
// it's not necessary that we use all types. for example
function makeUser<T,U>(name: T, age: U) : {name: T, age: string, isAdmin: boolean} {
return {
name: name,
age: String(age),
isAdmin: true
}
}
Pass generics in the interface
We can pass generics the same as we pass functions.
Use generics in class
the last example gives an error because we are passing T as a number. which means a type of age is a number. but during creating an object we pass a 24 in string.
A real-life example of generics
Let's say there is a class which is list data and add data.
End
I hope you guys enjoy reading. don't forget to like, comment, and ask doubt if have any. I also need your feedback to improve my writing. so feedback will be highly appreciated. That's it for the day. let's meet tomorrow with another gem article. Bye!!