Basic Usage of Generics in Typescript

by Nov 5, 2023typescript generics

Keypoints

  • Show how to declare generic functions and classes in TypeScript.
  • Provide examples of generic functions that work with different data types.
  • Demonstrate the use of built-in generics like Array<T> and Promise<T>.


Here’s the content for “Chapter 2: Basic Usage of Generics” in your TypeScript generics blog:


Basic Usage of Generics

Now that we have a solid understanding of what generics are and their historical context, it’s time to roll up our sleeves and dive into the practical world of TypeScript generics. In this chapter, we’ll explore the basics: declaring and using generic functions, demonstrating how they work with various data types, and leveraging built-in generics that TypeScript offers.

2.1 Declaring and Using Generic Functions

At the heart of TypeScript generics are generic functions. These functions provide a way to create code that can work with a variety of data types. Let’s start by understanding the fundamental steps of declaring and using generic functions.

To declare a generic function, you use the angle brackets (< >) notation, often referred to as type parameters. Here’s a simple example:

function identity<T>(arg: T): T {
  return arg;
}

In this example, T is a type parameter. It serves as a placeholder for the actual data type that will be provided when the function is called. The type parameter T allows us to keep the function flexible while ensuring type safety.

Now, let’s use the identity function with different data types:

let value1 = identity<string>("Hello, TypeScript"); // Returns a string
let value2 = identity<number>(42); // Returns a number

As you can see, we call the identity function by specifying the type parameter within angle brackets. TypeScript infers the data type of the return value based on the type parameter we provide.

2.2 Generic Functions with Different Data Types

Generic functions truly shine when you need to work with various data types in a type-safe manner. Let’s explore how we can use generic functions with different data types:

function getLength<T>(input: T[]): number {
  return input.length;
}

const numbers = [1, 2, 3, 4, 5];
const fruits = ["apple", "banana", "cherry"];

const numCount = getLength(numbers); // Returns 5
const fruitCount = getLength(fruits); // Returns 3

In this example, the getLength function takes an array of any data type and returns the length of the array. We don’t need to specify the data type explicitly when calling the function; TypeScript infers it based on the type of the argument.

2.3 Utility of Built-In Generics: Array<T> and Promise<T>

TypeScript offers a set of built-in generics that simplify common tasks. Two notable examples are Array<T> and Promise<T>.

  • Array<T>: The Array<T> type allows you to create arrays that contain elements of a specific data type. This ensures that the array only contains elements of that type. For instance:
const numbers: Array<number> = [1, 2, 3, 4, 5];
const names: Array<string> = ["Alice", "Bob", "Charlie"];
  • Promise<T>: Promises represent asynchronous operations that will eventually produce a result or an error. By using Promise<T>, you can specify the expected data type of the resolved value. For example:
function fetchUserData(): Promise<User> {
  // Fetch user data asynchronously and return a User object
}

These built-in generics enhance code readability and provide type safety, reducing the likelihood of runtime errors.

With a solid grasp of declaring and using generic functions, as well as understanding the utility of built-in generics like Array<T> and Promise<T>, you’ve taken a significant step toward mastering TypeScript generics. In the next chapter, we’ll explore type constraints and extending generics, allowing us to fine-tune our generic code for even more specific use cases.

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

Advanced Generics: Higher-Order Functions

Advanced Generics: Higher-Order Functions

In our journey through TypeScript generics, we've covered the basics, interfaces, and classes. Now, it's time to explore advanced concepts by combining generics with higher-order functions. These functions, which take other functions as arguments or return them,...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....