DEV Community

iamndeleva
iamndeleva

Posted on

2

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())

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay