Using Constraints and Defaults in Generics

Tutorial 3 of 5

Introduction

Goal

This tutorial aims to provide a comprehensive understanding of how to use constraints and default values in generics within TypeScript.

Learning Outcomes

By the end of this tutorial, you will be able to:
- Define and understand what generics are
- Understand the importance of constraints in generics
- Use default values in generics
- Apply these concepts in your TypeScript programs

Prerequisites

Basic understanding of TypeScript and programming concepts such as variables, data types, and functions are necessary. Knowledge of generics would be beneficial but not mandatory as we will cover it briefly.

Step-by-Step Guide

Generics

Generics allow you to create reusable components that can work with different types. They are like variables for types. A common example is an array, which can hold different types of values.

let arr: Array<number> = [1, 2, 3];

In this example, Array is a generic that is being used with the type number.

Constraints in Generics

Constraints are a way to limit the types that can be used with generics. You can use the extends keyword to enforce a constraint.

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

Here, T is constrained to types that have a length property of type number.

Default Values in Generics

Default values in generics are used when no type argument is provided or when undefined is passed in. You can specify a default value by using = after the generic type.

function getArray<T = number>(): T[] {
    return [];
}

In this example, if no type argument is provided when calling getArray, number will be used.

Code Examples

Example 1: Using Constraints

function logLength<T extends { length: number }>(arg: T): T {
    console.log(arg.length); // Logs the length of arg
    return arg; // Returns the argument
}

let arr = logLength([1, 2, 3]); // Logs 3, arr is of type 'number[]'
let str = logLength('Hello'); // Logs 5, str is of type 'string'

In this example, we have a function logLength that takes a single argument arg of a generic type T. The generic type T is constrained to only types that have a length property that is a number.

Example 2: Using Default Values

function getArray<T = number>(): T[] {
    return []; // Returns an empty array
}

let arr1 = getArray(); // arr1 is of type 'number[]'
let arr2 = getArray<string>(); // arr2 is of type 'string[]'

In this example, the function getArray returns an array of a generic type T. If no type argument is provided when calling getArray, it defaults to number.

Summary

In this tutorial, we covered the use of constraints and default values in generics. We learned that constraints allow us to limit the types that a generic can use, while default values specify a type to use when none is provided.

For further learning, you can read more about generics in the TypeScript Handbook.

Practice Exercises

  1. Exercise 1: Create a function that accepts an array of a generic type and returns the first element. Use constraints to ensure the argument is an array.

  2. Exercise 2: Create a function that creates an object with a value property. The type of value should be a generic with a default value of string.

Solutions:

  1. typescript function getFirst<T extends any[]>(arg: T): T[0] { return arg[0]; }
    In this solution, we constrain T to be an array of any type (any[]), and return the first element which is of type T[0].

  2. typescript function createObject<T = string>(value: T) { return { value }; }
    Here, we create an object with a value property whose type is a generic T with a default value of string.

Keep practicing and exploring more about generics, constraints, and default values. Happy coding!