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…
Section overview
5 resourcesExplains 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
-
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.
-
Exercise 2: Create a function that creates an object with a
valueproperty. The type ofvalueshould be a generic with a default value ofstring.
Solutions:
-
typescript function getFirst<T extends any[]>(arg: T): T[0] { return arg[0]; }
In this solution, we constrainTto be an array of any type (any[]), and return the first element which is of typeT[0]. -
typescript function createObject<T = string>(value: T) { return { value }; }
Here, we create an object with avalueproperty whose type is a genericTwith a default value ofstring.
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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article