Tutorial Playlist

Programming Tutorial

Overview

Your Guide to the Best Backend Languages for 2021

Lesson - 1

An Ultimate Guide That Helps You to Start Learn Coding 2022

Lesson - 2

What is Backend Development : The Ultimate Guide for Beginners

Lesson - 3

All You Need to Know for Choosing the First Programming Language to Learn

Lesson - 4

Here’s All You Need to Know About Coding, Decoding, and Reasoning With Examples

Lesson - 5

Understanding What Is XML: The Best Guide to XML and Its Concepts.

Lesson - 6

An Ultimate Guide to Learn the Importance of Low-Code and No-Code Development

Lesson - 7

Top 8 Frontend Languages That You Should Know About

Lesson - 8

Top 50+ Frontend Developer Interview Questions and Answers

Lesson - 9

The Ultimate Guide to Learn Typescript Generics

Lesson - 10

The Most Comprehensive Guide for Beginners to Know ‘What Is TypeScript’

Lesson - 11

The Ultimate Guide on Introduction to Competitive Programming

Lesson - 12

TCS Interview Process and Top 50 TCS NQT Interview Questions to Crack an Interview

Lesson - 13

Most Commonly Asked Logical Reasoning Questions in an Aptitude Test

Lesson - 14

Everything You Need to Know About Advanced Typescript Concepts

Lesson - 15

An Absolute Guide to Build C Hello World Program

Lesson - 16

A One-Stop Solution Guide to Learn How to Create a Game in Unity

Lesson - 17

What Is NAT? Significance of NAT for Translating IP Addresses in the Network Model

Lesson - 18

A Real-Time Chat Application TypeScript Project Using Node.js as a Server

Lesson - 19

What Is Raspberry Pi? Here’s the Best Guide to Get Started

Lesson - 20

What Is Arduino? Here’s the Best Beginners Guide to Get Started

Lesson - 21

Arduino vs. Raspberry Pi: Which Is the Better Board?

Lesson - 22
The Ultimate Guide to Learn Typescript Generics

Building components with well-defined and consistent APIs that are also reusable is an essential part of software engineering. Components that can function with today's data, and tomorrow's data, will give you the most flexibility when it comes to constructing massive software systems.

Generics is the ability to design a component that can work over several types rather than a single one. It is one of the critical tools in the toolkit for creating reusable components in C# and Java languages. This enables users to use these components while also allowing them to utilize their kinds.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

What Is TypeScript Generics?

typescript_generics

TypeScript Generics is a tool for creating reusable components in TypeScript. Rather than working with a single data type, it builds a component that can interact with various data kinds. It enables users to consume these components while also using their own kinds. Generics ensure that the software is both adaptable and scalable over time.

Type safety is provided via generics without sacrificing performance or efficiency. The type variable in TypeScript is used to denote types and uses generics. Generic functions have the same type as non-generic functions, with type arguments specified first, as in function declarations.

You must write a type parameter between the open () and close (>) brackets in generics to build strongly typed collections. For example, generics make use of a separate type variable to represent types. Only related types of things are found in the generics collections.

You can construct generic classes, generic methods, and generic functions with TypeScript.

Why Do You Need TypeScript Generics?

You will now understand why you need TypeScript Generics, with an example.

Consider the below code without generics. The identity function is a function that returns whatever is sent in as a parameter. You could either provide the identity function with a specific type or the identity function with any type.

Identity function with a specific type

function identity(arg: string): string {

 return arg;

Identity function with any type

function identity(arg: any): any {

 return arg;

}

While the use of any is generic. When you use 'Any,' the function accepts any kind for the type of arg. As a result, when the function returns, you lose the information about what that type was. The only information you have is that any type could be produced if you pass in a string.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

You need the means to capture the argument type in such a way that you can use it to signify what is being returned as well. You will utilize a type variable here, which is a form of variable that deals with types rather than values.

function identity<Type>(arg: Type): Type {

  return arg;

}

The identity function now has a type variable called Type. This Type allows you to capture the type of data the user supplies, for example, a number or a string, so that you can use it later. You are going to utilize Type as the return type once more.

You can use one of two methods to invoke the generic identity function after writing it. The first method is to pass all the parameters to the function, including the type argument:

let output = identity<number>("Idnumber");

You specifically set Type to number as one of the function call's arguments, as shown by the > surrounding the arguments rather than the ().

The second method is you utilize type argument inference here, which means you want the compiler to automatically set the value of Type based on the type of the argument you pass in:

let output = identity("Idnumber");

Generic Types

Generic functions have the same type parameters as non-generic functions, with the type parameters listed first, as in function declarations:

function identity<Type>(arg: Type): Type {

  return arg;

}

let myIdentity: <Type>(arg: Type) => Type = identity;

You can call the generic type parameter in the type by whatever name you like as long as the number of type variables and how they're utilized match.

let myIdentity: <Input>(arg: Input) => Input = identity;

You can also write the generic type as a call signature of an object literal type:

let myIdentity: { <Type>(arg: Type): Type } = identity;

Generic Classes

A generic class resembles a generic interface in appearance. Following the name of the class, generic classes contain a generic type parameter list enclosed in angle brackets (>).

Although this is a relatively literal use of the GenericNumber class, you'll notice that nothing restricts it to using only the number type. Instead, you may have used string or even more complicated objects.

Putting the type parameter on the class itself, like the interface, ensures that all the class's properties function with the same type.

A class's type has two sides: a static side and an instance side. Generic classes are only generic on the instance side, not the static side, hence static members can't use the class's type parameter while working with them.

class GenericNumber<NumType> {

  zeroValue: NumType;

  add: (x: NumType, y: NumType) => NumType;

}

let myGenericNumber = new GenericNumber<number>();

myGenericNumber.zeroValue = 0;

myGenericNumber.add = function (x, y) {

  return x + y;

};

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Generic Constraints

TypeScript Generics Types allow you to work with any data type. You can, however, use constraints to limit it to specific types.

A type parameter can be declared that is limited by another type parameter. For instance, in this case, you would need to retrieve a property from an object based on its name. You must put a constraint between the two types to ensure you are not obtaining a property that doesn't exist on the obj.

function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) {

  return obj[key];

}

let x = { e: 5, f: 6, g: 7, g: 8 };

getProperty(x, "e");

getProperty(x, "m");

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

We hope that this tutorial on TypeScript generics has given you a fundamental grasp of the language, its types, classes, and constraints. Course certification will be helpful if you want to study these programming languages and possibly work as a developer or as a programmer. Enroll in the Full Stack Web Developer - MEAN Stack Master's program to learn typescript.

If you have any queries or questions about this tutorial on "TypeScript Generics," please contact us. Please leave your questions in the form below, and one of our experts will respond as soon as possible!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.