Reduce duplicate types with Generic Types

InstructorKamran Ahmed

Share this video with your friends

Send Tweet

TypeScript allows us to create reusable types called Generics i.e. creating types that can work as a variety of types. Let's say that we have a Box type which can hold different types of content i.e.

type Box = {
   name: string;
   content: string;
}

In the above type, we can only store the content of the type string. Using generic types, we can modify our type as follows to allow storing different types of content.

type Box<T> = {
   name: string;
   content: T;
}

// It can now be used as follows to store contents of type 
// string, number, boolean or any other type
type NumberBox = Box<number>;
type StringBox = Box<string>;
type BooleanBox = Box<boolean>;

In this lesson, we discuss how we can benefit from generic types to avoid duplicate types. You can also learn more about the Generic types in the TypeScript docs.