Creating Generic Functions and Interfaces

Tutorial 2 of 5

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.