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.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

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.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

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;

};

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

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");

Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer - MERN Stack Master's program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!

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 Developer - MERN Stack 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
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.