TypeScript / TypeScript Generics

Using Constraints and Defaults in Generics

In this tutorial, we will explore how to use constraints and default values with generics in TypeScript. These features provide more control over how your generic components behav…

Tutorial 3 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.

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!

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

Time Zone Converter

Convert time between different time zones.

Use tool

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

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