DEV Community

iamndeleva
iamndeleva

Posted on

Generics in typescript

when building react applications , writing reusable components is one of the key concept that is highly prioritized But most a times this components only receive a specific type that allows them to be reliable .Using Typescript allows you to write components that can have several types which makes it more flexible than opposed to the single type they had before .The concept of generics then comes in to bridge this gap
What are generics
In summary from the typescript official docs , generics let you write components that can take multiple types instead of one type .You define generics using <T> but in real sense you can name it whatever you like .
example in ES6
const myGeneric = <T>(params:T):T =>{}

for ES5
function myGeneric<T>(params:T):T{}

where T can be string ,array ,boolean etc
_lets define some interface here for IAnimal _
interface IAnimal{
type: string;
age:number;
eat: () => void;
}

class Dog implements IAnimal{
type = 'dog';
age=10;
eat(): void {
console.log('eating')
}
}
const results = <T extends IAnimal>(value:T):void=>{
console.log(value)
}
results(new Dog())

Top comments (0)