Generic

This lesson introduces generic types.

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.

Press + to interact
// 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 ...