Search⌘ K

Generic

Explore how generics in TypeScript enhance your ability to create reusable and type-safe components and structures. Understand the differences between generic types and the any type, and see practical examples such as generic lists and React component properties. This lesson helps you write cleaner, more maintainable code by enforcing type constraints while keeping flexibility.

We'll cover the following...

Introduction

Generic allows for improved reusability by parameterizing a type with another one. A popular front-end framework named React can have an unlimited number of components. They all have properties that are unique to their components. It would be tedious to have to inherit a base class or alter the framework to accommodate all potentials possibilities. Hence, the properties of these React components use a generic.

TypeScript 3.3.4
// Generic Component that has properties that can change depending of the implementation
interface MyComponent<TProps> {
name: string;
id: number;
props: TProps;
}
// First property that has a string
interface Props1 {
color: string;
}
// Second property that has a number
interface Props2 {
size: number;
}
// First component that has color in property because it is generic with Props1
const component1: MyComponent<Props1> = {
name: "My Component One",
id: 1,
props: { color: "red" }
};
// Second component that has size in property because it is generic with Props2
const component2: MyComponent<Props2> = {
name: "My Component Two",
id: 2,
props: { size: 100 }
};
console.log(component1);
console.log(component2);

Lines 19 and 26 are where the generic component takes ...