search
HomeWeb Front-endJS TutorialTypeScript Generics: A Complete Guide

TL;DR: TypeScript Generics allow developers to write reusable code that can work with various data types while maintaining type safety. They are essential for building robust and scalable TypeScript apps.

TypeScript Generics: A Complete GuideTo ensure the code is transparent and manageable, Typescript requires the safe and effective management of several kinds of data. One of Typescript’s core features is Typescript generics, which permits the creation of functions, classes, and interfaces while adhering to stringent type limitations. Generics allow you to write less code, make fewer mistakes, and, most importantly, build flexible components for different data types.

This article explores the essentials of typescript generics, including their usage in functions, classes, and interfaces, and demonstrates how they make code versatile and robust.

What are Typescript generics?

Typescript generics can define typescript code with placeholder types, allowing it to be flexible, extensible, and reusable while remaining type-safe.

Typescript makes type safety checks during compile time as a placeholder that defines a generic type. When the component is implemented, the actual type replaces the placeholder. This technique makes managing and decreasing duplicity easier because you don’t need distinct implementations for each data type.

Without generics, you would write multiple versions of a function or class to handle different data types, leading to code duplication. Generics allow for a single implementation that is reusable to various kinds while retaining static type checking.

The code examples in the next section will help you to understand this difference.

When to use Typescript generics?

Generics can be used across different parts of typescript to help manage types more efficiently. They’re instrumental in functions, interfaces, classes, and other structures where flexibility is critical.

1. Generic types in functions

Generics are often applied in functions to reduce redundancy. For example, consider a function that takes a string or a number as a parameter.

function identity(value: any): any {
  return value;
}
const result1 = identity(42); // result1: any
const result2 = identity("hello"); // result2: any

This function works fine. But it uses any type, which means the Typescript loses track of the specific type. As a result, the return value is typed as any, and Typescript can no longer enforce type safety. If we need to maintain type safety, we would have to write two different functions, with one returning a string while the other returns a number. However, that approach will increase code duplication.

We can improve the above function by using generics to preserve type information.

function identity(value: any): any {
  return value;
}
const result1 = identity(42); // result1: any
const result2 = identity("hello"); // result2: any

The T represents the type that the method uses in this case. If present, Typescript will confirm that the input type and the type in the return parameter are the same.

Also, we can define the function without explicitly defining the parameter type.

function identity<t>(value: Type): T {
  return value;
}
const result1 = identity<number>(42); // result1: number
const result2 = identity<string>("hello"); // result2: string
</string></number></t>

In Typescript, you can use more than one generic type parameter when working with multiple types in a single function or component. For example, you might want a function that takes two different types of inputs and returns them as a pair.

const result3 = identity(100); // result3: number
const result4 = identity("world"); // result4: string

In this case, the function returns a tuple with a first element of type T and a second element of type U. This enables type-safe handling of two distinct types by the function.

2. Default types in typescript

In Typescript, you can provide a default type for a generic, making it optional. If no type is provided, Typescript will use the default.

function multipleParams<t u>(first: T, second: U): [T, U] {
 return [first, second];
}
const result1 = multipleParams<string number>("hello", 42); // result1: [string, number]
const result2 = multipleParams<string number>("hello", "world"); // result2: gives a type error
</string></string></t>

In this example, the type parameter T defaults to string. If the developer doesn’t indicate a specific type when they call the function, T will be a string by default.

3. Generic interfaces

Typescript generics can also be applied to interfaces. Imagine you want to define a Box interface with a value of any type.

function createArray<t string>(length: number, value: T): T[] {
 return Array(length).fill(value);
}

const stringArray = createArray(3, "hello"); // T defaults to string, so stringArray is a string array
const numberArray = createArray<number>(3, 42); // T is explicitly set to a number, so numberArray is a number array
</number></t>

This is more equal to the generic functions example; this code will also work without issues since we have not defined a specific type. But, because the value is typed as any, we may encounter type-related bugs.

To secure the type, we can define a generic interface here.

interface Box {
  value: any;
}
const numberBox: Box = { value: 123 }; // correct
const stringBox: Box = { value: "hello" }; // correct

The interface is generic, and its value type is strictly constrained to the Type variable. The Type variable can be specified as a number or string while creating an instance so that the Typescript ensures that appropriate types are adhered to.

4. Generic classes

Classes can also be written using generics to handle different types while maintaining type safety. Let’s create a Storage class that can store and retrieve values of any type.

interface Box<type> {
  value: Type;
}
const numberBox: Box<number> = { value: 123 }; // number
const stringBox: Box<string> = { value: "hello" }; // string
const stringBox2: Box<string> = { value: 123 }; // incorrect
</string></string></number></type>

This class works, but since data is of type any, the getItem method returns any, removing type safety. So, we can rewrite the class using generics to improve type safety.

class Storage {
  private data: any;
  setItem(item: any): void {
    this.data = item;
  }
  getItem(): any {
    return this.data;
  }
}
const storage = new Storage();
storage.setItem(123);
const item = storage.getItem();

In this case, the type T is used by the Storage class. Typescript ensures that the data is correct when you define the type for them when you create an instance. The getItem method in this code example will yield a number.

5. Generic constraints

You can use generic constraints to restrict the types that a generic can accept, ensuring they have specific properties.

For example, if you have a function that needs to access the length property of an input, you can use a constraint to ensure that only types with a length property are allowed. This prevents Typescript from giving errors or letting incompatible types slip through.

function identity(value: any): any {
  return value;
}
const result1 = identity(42); // result1: any
const result2 = identity("hello"); // result2: any

Here, value T is not defined with length property. To ignore the issue, we can add a constraint specifying that T must have a length property. We do this by saying T extends { length: number }.

function identity<t>(value: Type): T {
  return value;
}
const result1 = identity<number>(42); // result1: number
const result2 = identity<string>("hello"); // result2: string
</string></number></t>

Now, this function will have the length property; it will not give any errors and will execute with the length of the input.

Conclusion

Typescript generics allow you to write code that is flexible, recyclable, and type-safe. You can manage many data types without repeating code using classes, methods, and interfaces with these generics. Generic constraints, numerous types, and default types are some of the key use cases we looked at in this post and showed how each can improve the scalability and maintainability of programs.

Understanding Typescript generics can help you write more precise, adaptable, and type-safe code, making your Typescript applications more robust.

Related Blogs

  • Webpack vs Vite: Which Bundler is Right for You?
  • Build Micro Frontends with single-spa: A Guide
  • Master Asynchronous JavaScript with RxJS
  • Axios and Fetch API? Choosing the Right HTTP Client

The above is the detailed content of TypeScript Generics: A Complete Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment