TypeScript / TypeScript Generics

Creating Generic Functions and Interfaces

This tutorial will guide you through the process of creating generic functions and interfaces in TypeScript. These generic components will allow you to handle a variety of types w…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explains how to use generics to create reusable and type-safe components in TypeScript.

1. Introduction

In this tutorial, we will delve into the world of TypeScript, a statically typed superset of JavaScript, with a focus on creating generic functions and interfaces. The goal is to develop a firm understanding of these concepts and apply them to handle a variety of types with a single piece of code.

By the end of this tutorial, you will learn:

  • What generics are in TypeScript
  • How to create generic functions and interfaces
  • How to apply these concepts in practical scenarios

Prerequisites: Basic understanding of TypeScript and JavaScript, including types, functions, and interfaces.

2. Step-by-Step Guide

Generic Functions

In TypeScript, a generic function is a function that can work on a variety of data types while keeping type safety. Let's see how we can create a generic function.

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

In the above code:
- T is a type variable. We use it as a placeholder for the actual type.
- arg is a parameter of type T.
- The function identity returns a value of type T.

We can call this function with any type, and TypeScript will ensure type safety:

let output = identity<string>("myString");  // type of output will be 'string'

Generic Interfaces

Just like functions, we can also create generic interfaces in TypeScript. Here is a simple example:

interface GenericIdentityFn<T> {
    (arg: T): T;
}

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

let myIdentity: GenericIdentityFn<number> = identity;

In this code:
- GenericIdentityFn is a generic interface with a single member.
- The member is a function that takes an argument (arg) of type T and returns a value of type T.
- myIdentity is a function that matches the structure of GenericIdentityFn, and it can handle number type.

3. Code Examples

Let's take a look at another example of generic function and interface.

Generic Function

function loggingIdentity<T>(arg: T[]): T[] {
    console.log(arg.length); 
    return arg;
}

loggingIdentity([1, 2, 3]); // Output: 3

In this function, we are working with arrays. The function logs the length of the array and returns the array.

Generic Interface

interface Lengthwise {
    length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length); 
    return arg;
}

loggingIdentity({length: 10, value: 3}); // Output: 10

In this example, we have a generic interface Lengthwise with a single member length. The generic function loggingIdentity now works on any object that has a length property.

4. Summary

In this tutorial, we've learned about generic functions and interfaces in TypeScript. We've seen how they provide flexibility while keeping type safety. We've also looked at several code examples demonstrating these concepts.

For further learning, consider exploring more complex usage of generics, such as generic classes, generic constraints, and using type parameters in generic constraints.

Additional resources:

5. Practice Exercises

  1. Create a generic function that can swap the values of a pair (tuple of two elements). Test it with pairs of different types.
  2. Create a generic interface for a function that can compare two elements. Implement it for numbers and strings.

Solutions:

function swap<T, U>(pair: [T, U]): [U, T] {
    return [pair[1], pair[0]];
}
console.log(swap([1, "two"])); // Output: ["two", 1]
interface Comparator<T> {
    (a: T, b: T): number;
}

let numberComparator: Comparator<number> = (a, b) => a - b;
let stringComparator: Comparator<string> = (a, b) => a.localeCompare(b);

console.log(numberComparator(5, 3));  // Output: 2
console.log(stringComparator("a", "b"));  // Output: -1

Keep practicing with different types and scenarios to get comfortable with TypeScript generics.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Favicon Generator

Create favicons from images.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help