Table of contents
1.
Introduction
2.
Generics in Typescript
3.
Parameters in Generic Constraints
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Generic Constraints

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Typescript is a programming language that Microsoft developed. It is like a superset of the more commonly used Javascript. Typescript is designed for the development of very large-scale applications. Since it is a superset of Javascript, existing Javascript programs are also valid in Typescript. Typescript files are saved with the .ts extension.

Generics in Typescript

Generics is a Typescript tool that provides the user ways to create reusable components. Generics make components that allow the user to work with various data types. Generics ensures that the Typescript program is scalable for long-term use and makes sure it is flexible.

Let us look at an example of Generics to understand it better,

function numberOrString<T>(toCheck: T): T {    
    return toCheck;    
}    
let str = numberOrString<string>("CodingNinja");    
let num = numberOrString<number>( 1001 );  
console.log(str + ", Type of variable is : " +typeof(str));  
console.log(num+ ", Type of variable is : " +typeof(num));  

To create a Generic Type function, we add the open and close angular brackets (<>) in front of the function name and pass a variable in the brackets. In our case, we have used T. In the above code snippet for the variable “str,” the input and return type of the function is a string, and for the variable “num,” the input and return type of the function is a number.

Sometimes in Typescript, we want to work with types with a particular property rather than working with all the data types, so here we use the Constraint property of Generics to achieve this requirement.

Let us look at an example of Generic Constraints,

Suppose we wanted a Generic function that returns the length of a string. We will need to constrain the function to accept only data types with the “.length” property.

interface Length{
  length: number;
}
function find_length<T extends Length>(inp: T): T {
  return inp;
}
var len = find_length(3);
console.log("Length of the string is: "+len.length);

In the above example, we passed a number value to the function, and the compiler returned an error.

interface Length{
  length: number;
}
function find_length<T extends Length>(inp: T): T {
  return inp;
}
var len = find_length("Hey Ninja");
console.log("Length of the string is: "+len.length);

And when we passed a string value, the compiler successfully compiled the code and returned the length of the string.

Parameters in Generic Constraints

Generic Constraints can also be achieved by using type parameters that are already constrained by another type parameter. Let’s understand this concept with an example,

function getOption<T, Key extends keyof T>(arr: T, key: Key) {
  return arr[key];
}
let options = { 
    1: "option 1", 
    2: "option 2", 
    3: "option 3", 
    4: "option 4"
};
var output = getOption(options, 1);
console.log("Selected option is: "+output);

In this code snippet, we grab the properties existing in the options object and then return the value corresponding to the property mentioned in the function call.

FAQs

  1. What are Generics?
    Generics is a Typescript tool that provides the user ways to create reusable components. Generics make components that allow the user to work with various data types. Generics ensures that the Typescript program is scalable for long-term use and makes sure it is flexible.
     
  2. What are Generic Constraints?
    Sometimes in Typescript, we want to work with types with a particular property rather than working with all the data types, so here we use the Constraint property of Generics to achieve this requirement.

Key Takeaways

This Blog covered all the necessary points about Generic Constraints in Typescript, discussing in-depth its functionality and the methods of the appliance of Generic Constraints. And also its implementation in Typescript.

Don't stop here; check out Coding Ninjas for more unique courses and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and fantastic Data Structures and Algorithms problems.

Live masterclass