DEV Community

Usaid
Usaid

Posted on

8 2 1 3 1

Generics in TypeScript

Generics in TypeScript allow you to write functions and classes that can work with a variety of data types while maintaining type safety. They provide a way to create reusable and type-safe components, offering a level of abstraction that promotes code flexibility.

Let's start by looking at a simple example. Consider a function that returns the input it receives:

const num = 1;
const str = 'a';
function returnValue(val: any): any {
 return val
};

const numReturn = returnValue(num);
const strReturn = returnStr(str);
Enter fullscreen mode Exit fullscreen mode

While this works, it lacks type safety. The any type means that the function can accept any type of argument, but it doesn't provide information about the type of the returned value. This is where generics come into play.

Generics allow us to create functions and classes that can work with different data types while preserving type information. Let's rewrite the returnValue function using generics:

function returnValue<T>(val: T): T {
 return val
};

const numReturn = returnValue(21)
Enter fullscreen mode Exit fullscreen mode

In this example, the T inside the angle brackets represents a type parameter. The type parameter T acts as a placeholder for the actual type that will be provided when the function is called. In the case of returnValue(21), T is inferred to be number (If you pass a string it will be taken as a string).

Benefits:

  • Type Safety: With generics, you can write code that is both flexible and type-safe. The TypeScript compiler can catch type-related errors at compile time, providing a safety net that plain JavaScript lacks.

  • Code Reusability: Generics allow you to create functions and classes that can work with different types without sacrificing reusability. This can lead to more modular and maintainable code.

  • Functionality Abstraction: Generics enable the creation of highly abstracted and versatile components. You can write code that doesn't depend on specific types, making it adaptable to a wide range of scenarios.

  • Improved Readability: By using generics, your code becomes more expressive and readable. Type parameters provide meaningful names for the types involved, making the code easier to understand.
    Conclusion:

In this introductory guide, we've explored the basics of generics in TypeScript. As you delve deeper into TypeScript development, generics will become an essential tool in your toolkit for writing robust, reusable, and type-safe code. By leveraging generics, you can enhance the flexibility and maintainability of your TypeScript projects, making them more scalable and easier to work with in the long run.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (2)

Collapse
 
harsh0703 profile image
Harsh

Tip: if you want only numbers and strings to be allowed for this function,then you can do this.
generics:
function returnValue(val: T extends string | number): T {
return val
};

Collapse
 
usaidpeerzada profile image
Usaid

Thanks mate! I will be posting more about Generics (Beginner to advanced). Stay tuned.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay