- Expert Angular
- Mathieu Nayrolles Rajesh Gunasundaram Sridhar Rao
- 237字
- 2021-07-15 17:05:33
Generics
Generics are very useful for developing reusable components that can work against any data type. So, the client that consumes this component will decide what type of data it should act upon. Let's create a simple function that returns whatever data is passed to it:
function returnNumberReceived(arg: number): number { return arg; }
unction returnStringReceived(arg: string): string { return arg; }
As you can see, we need individual methods to process each data type. We can implement them in a single function using the any data type, as follows:
function returnAnythingReceived (arg: any): any { return arg; }
This is similar to generics. However, we don't have control over the return type. If we pass a number and we can't predict whether the number will be returned or not by the function, the return type can be of any type.
Generics offers a special variable of type T. Applying this type to the function as follows enables the client to pass the data type they would like this function to process:
function returnWhatReceived<T>(arg: T): T { return arg; }
So, the client can call this function for various data types as follows:
var stringOutput = returnWhatReceived<string>("return this"); // type of output will be 'string' var numberOutput = returnWhatReceived<number>(101); // type of output will be number
- Advanced Quantitative Finance with C++
- Getting Started with Gulp(Second Edition)
- Python進階編程:編寫更高效、優(yōu)雅的Python代碼
- 高級C/C++編譯技術(典藏版)
- Python機器學習:手把手教你掌握150個精彩案例(微課視頻版)
- Hands-On Enterprise Automation with Python.
- 青少年信息學競賽
- 響應式Web設計:HTML5和CSS3實戰(zhàn)(第2版)
- Spring+Spring MVC+MyBatis從零開始學
- Hands-On Nuxt.js Web Development
- 新印象:解構UI界面設計
- Visual Basic程序設計(第三版)
- ASP.NET Web API Security Essentials
- 大學計算機基礎實訓教程
- Drupal 8 Development Cookbook(Second Edition)