Introduction to TypeScript Generics

Understand what generics are and how they help us build strongly typed polymorphic components.

We'll cover the following

Introduction

We will now begin to leverage TypeScript to build strongly typed polymorphic components.

The first two requirements we start off with are:

  • The as prop should not receive invalid HTML element strings.

  • Incorrect attributes should not be passed for valid elements.

TypeScript generics

TypeScript generics are an integral part of the final solution for our strongly typed polymorphic component.

A simple mental model for approaching generics is to see them as special variables for our types. Where JavaScript has variables, Typescript has generics (for types).

Let’s have a look at a classic example.

Below is an echo function, where v represents any arbitrary value.

Get hands-on with 1400+ tech skills courses.