Logo

dev-resources.site

for different kinds of informations.

Demystifying TypeScript Generics with Simple Examples

Published at
9/30/2023
Categories
typescript
javascript
ts
webdev
Author
xanyl
Categories
4 categories in total
typescript
open
javascript
open
ts
open
webdev
open
Author
5 person written this
xanyl
open
Demystifying TypeScript Generics with Simple Examples

TypeScript Generics can seem daunting at first, but they are a powerful tool for creating flexible and type-safe code. In this article, we'll explore Generics through easy-to-understand examples, breaking down the concepts step by step.

What Are Generics?

Generics in TypeScript allow you to write code that can work with different data types while still maintaining type safety. Think of them as placeholders for types that you specify when you use them.

Generic Functions

Let's start with the basics by looking at generic functions:

function echo<T>(arg: T): T {
    return arg;
}
Enter fullscreen mode Exit fullscreen mode

Here, echo is a generic function. The <T> part inside the parentheses declares that T is a type parameter. It's like saying, "I'll tell you the type later."

Now, when you call echo and provide an argument, TypeScriptfigures out the type based on what you pass:

let result = echo("Hello, TypeScript"); // result is of type 'string'
Enter fullscreen mode Exit fullscreen mode

In this case, result is automatically recognized as a string because we passed a string as an argument.

Generic Classes

Generics aren't limited to functions; you can also use them with classes. Consider a simple example of a generic class Box:

class Box<T> {
    private value: T;

    constructor(value: T) {
        this.value = value;
    }

    getValue(): T {
        return this.value;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this class, T is a type parameter that represents the type of the value property. When you create a Box instance, you specify the type it will hold:

let numberBox = new Box<number>(42); // numberBox can only hold numbers
let stringBox = new Box<string>("Hello, TypeScript"); // stringBox can only hold strings
Enter fullscreen mode Exit fullscreen mode

TypeScript ensures that you can't mix types within a Box. Trying to do so would result in a compile-time error.

Real-World Applications

Now that you've grasped the basics, let's see where Generics can be valuable:

1.Array Functions: Many array methods like map, filter, and reduce use Generics under the hood to work with different element types.

  1. Promises: Promises can return various types of values, and Generics help define the expected return type when using Promise<T>.

  2. React Components: Creating reusable components that can work with different data types as props.

  3. API Requests: When fetching data from an API, Generics can specify the expected shape of the response data.

Conclusion

Generics might appear complex at first glance, but they're a valuable tool for writing versatile and type-safe code. By using them, you can create functions, classes, and data structures that adapt to different types while catching type errors early in the development process. As you become more comfortable with Generics, you'll find them indispensable in building robust and maintainable TypeScript applications.

ts Article's
30 articles in total
Favicon
How to improve the Frontend part of the project using one button as an example :))))
Favicon
Azure App Service doesn't returned compressed (gzip) files for Angular application?
Favicon
Deploying a Simple Static Website on AWS with CDK and TypeScript
Favicon
Understanding Next.js and TypeScript Tutorial
Favicon
🛠️📚 Classes with TypeScript - a cheat sheet
Favicon
Event Loop in 2 Minutes
Favicon
How Boring It Is to Write Articles or Talk to Certain Types of Developers These Days.
Favicon
How ts-pattern can improve your code readability?
Favicon
isNaN vs Number.isNaN
Favicon
🛠️ 📦 TypeScript Generics - a cheat sheet
Favicon
TypeScript Generics: How to Write Flexible and Type-Safe Code
Favicon
Introduction to TypeScript
Favicon
Dominando os Utility Types do TypeScript
Favicon
Nega aynan Vue.js ?
Favicon
TS-BoilerplateX
Favicon
What Are Standalone Components Angular 17 ?
Favicon
Navigating the JS TS Limbo
Favicon
Demystifying TypeScript Generics with Simple Examples
Favicon
Typescript enum vs. "as const"
Favicon
Mastering TypeScript: A Comprehensive Tutorial
Favicon
m3u8 to mp4 with merged audio
Favicon
Shouldn't an NPM package that helps hundreds of thousands of programmers increase their productivity tenfold be open-sourced?
Favicon
ChatGPT: how I used it to convert HTTP requests to OpenAPI document
Favicon
Cleaning up unused Typescript Files with `ts-prune`
Favicon
Intern's Guide Chat GPT Full Stack: Nest, React, Typescript
Favicon
Using LiteFS with Bun on Fly.io
Favicon
Know your users' location in React Ts
Favicon
Regex #1: Understanding Regex, Regex-Based String Methods and Regex Flags
Favicon
The Witcher Card Game Live
Favicon
Powerful File System manager for Nodejs

Featured ones: