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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay