YiXu Zhang

YiXu Zhang


Understanding TypeScript Generics

An introduction to the utilization of Generics in TypeScript with examples grounded in real-world use cases, such as collections, approaches to error handling, the Repository Pattern, and so on. This article hopes to provide an intuitive understanding of the notion of software abstraction through Generics.

In this article, we’ll be learning the concept of Generics in TypeScript and examining how Generics can be used to write modular, decoupled, and reusable code. Along the way, we’ll briefly discuss how they fit into better testing patterns, approaches to error handling, and domain/data-access separation.

A Real-World Example

I want to enter into the world of Generics not by explaining what they are, but rather by providing an intuitive example for why they are useful. Suppose you’ve been tasked with building a feature-rich dynamic list. You could call it an array, an ArrayList, a List, a std::vector, or whatever, depending upon your language background. Perhaps this data structure must have in-built or swappable buffer systems as well (like a circular buffer insertion option). It will be a wrapper around the normal JavaScript array so that we can work with our structure instead of plain arrays.

The immediate issue you’ll come across is that of constraints imposed by the type system. You can’t, at this point, accept any type you want into a function or method in a nice clean way (we’ll revisit this statement later).

The only obvious solution is to replicate our data structure for all different types:

const intList = IntegerList.create();

const stringList = StringList.create();

const userList = UserList.create();
userList.add(new User('Jamie'));

The _.create()_ syntax here might look arbitrary, and indeed, _new SomethingList()_ would be more straight-forward, but you’ll see why we use this static factory method later. Internally, the _create_ method calls the constructor.

This is terrible. We have a lot of logic within this collection structure, and we’re blatantly duplicating it to support different use cases, completely breaking the DRY Principle in the process. When we decide to change our implementation, we’ll have to manually propagate/reflect those changes across all structures and types we support, including user-defined types, as in the latter example above. Suppose the collection structure itself was 100 lines long — it would be a nightmare to maintain multiple different implementations where the only difference between them is types.

An immediate solution that might come to mind, especially if you have an OOP mindset, is to consider a root “supertype” if you will. In C#, for example, there consists a type by the name of object, and object is an alias for the System.Object class. In C#’s type system, all types, be they predefined or user-defined and be they reference types or value types, inherit either directly or indirectly from System.Object. This means that any value can be assigned to a variable of type object (without getting into stack/heap and boxing/unboxing semantics).

In this case, our issue appears solved. We can just use a type like any and that will allow us to store anything we want within our collection without having to duplicate the structure, and indeed, that’s very true:

const intList = AnyList.create();

const stringList = AnyList.create();

const userList = AnyList.create();
userList.add(new User('Jamie'));

Let’s look at the actual implementation of our list using any:

class AnyList {
    private values: any[] = [];

    private constructor (values: any[]) {
        this.values = values;

        // Some more construction work.

    public add(value: any): void {

    public where(predicate: (value: any) => boolean): AnyList {
        return AnyList.from(this.values.filter(predicate));

    public select(selector: (value: any) => any): AnyList {
        return AnyList.from(this.values.map(selector));

    public toArray(): any[] {
        return this.values;

    public static from(values: any[]): AnyList {
        // Perhaps we perform some logic here.
        // ...

        return new AnyList(values);

    public static create(values?: any[]): AnyList {
        return new AnyList(values ?? []);

    // Other collection functions.
    // ...

#typescript #javascript #web-development #programming #developer

What is GEEK

Buddha Community

Understanding TypeScript Generics

Guide to Understanding Generics in Java


Java is a type-safe programming language. Type safety ensures a layer of validity and robustness in a programming language. It is a key part of Java’s security to ensure that operations done on an object are only performed if the type of the object supports it.

Type safety dramatically reduces the number of programming errors that might occur during runtime, involving all kinds of errors linked to type mismatches. Instead, these types of errors are caught during compile-time which is much better than catching errors during runtime, allowing developers to have less unexpected and unplanned trips to the good old debugger.

Type safety is also interchangeably called strong typing.

Java Generics is a solution designed to reinforce the type safety that Java was designed to have. Generics allow types to be parameterized onto methods and classes and introduces a new layer of abstraction for formal parameters. This will be explained in detail later on.

There are many advantages of using generics in Java. Implementing generics into your code can greatly improve its overall quality by preventing unprecedented runtime errors involving data types and typecasting.

This guide will demonstrate the declaration, implementation, use-cases, and benefits of generics in Java.

#java #guide to understanding generics in java #generics #generics in java #guide to understanding generics in java

The Definitive Guide to TypeScript & Possibly The Best TypeScript Book

TypeScript Deep Dive

I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack Overflow / DefinitelyTyped and general engagement with the TypeScript community. You can follow for updates and don't forget to ★ on GitHub 🌹


  • Thanks for the wonderful book. Learned a lot from it. (link)
  • Its probably the Best TypeScript book out there. Good Job (link)
  • Love how precise and clear the examples and explanations are! (link)
  • For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. (link)
  • Just a big thank you! Best TypeScript 2 detailed explanation! (link)
  • This gitbook got my project going pronto. Fluent easy read 5 stars. (link)
  • I recommend the online #typescript book by @basarat you'll love it.(link)
  • I've always found this by @basarat really helpful. (link)
  • We must highlight TypeScript Deep Dive, an open source book.(link)
  • Great online resource for learning. (link)
  • Thank you for putting this book together, and for all your hard work within the TypeScript community. (link)
  • TypeScript Deep Dive is one of the best technical texts I've read in a while. (link)
  • Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. (link)
  • Thanks to @basarat for this great #typescript learning resource. (link)
  • Guyz excellent book on Typescript(@typescriptlang) by @basarat (link)
  • Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment (link)
  • numTimesPointedPeopleToBasaratsTypeScriptBook++; (link)
  • A book not only for typescript, a good one for deeper JavaScript knowledge as well. link
  • In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! link
  • Thank you for writing TypeScript Deep Dive. I have learned so much. link
  • Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! link
  • Microsoft doc is great already, but if want to "dig deeper" into TypeScript I find this book of great value link
  • Thanks, this is a great book 🤓🤓 link
  • Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks link
  • @basarat's intro to @typescriptlang is still one of the best going (if not THE best) link
  • This is sweet! So many #typescript goodies! link

Get Started

If you are here to read the book online get started.


Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.

Other Options

You can also download one of the Epub, Mobi, or PDF formats from the actions tab by clicking on the latest build run. You will find the files in the artifacts section.

Special Thanks

All the amazing contributors 🌹


Share URL: https://basarat.gitbook.io/typescript/

Author: Basarat
Source Code: https://github.com/basarat/typescript-book/ 
License: View license

#typescript #opensource 

John David

John David


How to Build Generic React Components with Typescript Generics

In this video tutorial, Santiago will show how to use Typescript Generics to build Generic React Components. Do you find yourself duplicating your code to do the same things multiple times? 
When building frontend applications, you may need to represent different entries in similar instances, for example aggregating search results within a single list. Separate typescript components are best to achieve this, but it can create problems such as code duplication which can slow down the process. Typescript generics provide an efficient solution to this problem by creating generic components.

0:00 - Intro
0:46 - Code Example
1:22 - Component Breakdown
3:58 - Using the Component

✔️ Santiago's code: https://codesandbox.io/s/typescript-generic-components-2zrus?file=/src/SelectList.tsx 

#typescript #generics #react 

Verdie  Murray

Verdie Murray


Why Generics? - JavaScript DataStructures and Algorithms in TypeScript

In this lesson we look at the key reason #generic type annotations are critical to maintainable type safe data structure creation in JavaScript / TypeScript

#JavaScript #typescript 

Adnan Malik


TypeScript Generics Tutorial | Understanding Generics

In order to fully harness the power of TypeScript, you need to take advantage of all the tools it provides for developing reusable, type-safe code. In “Creating and Using Generics in TypeScript”, you will learn how to do more with less code. You will learn what generics are, how to recognize and use built-in generic types, and how to create your own generic functions, interfaces, and classes. When you are finished with this course, you will have a foundational understanding of TypeScript generics as well as the skills to begin using generics to build sophisticated web applications.

Subscribe: https://www.youtube.com/channel/UCmzhBmJCV6okfm8Sx-zElrg/featured