- Angular UI Development with PrimeNG
- Sudheer Jonna Oleg Varaksin
- 152字
- 2021-07-15 17:32:54
Generics
In TypeScript, you can define generic functions, interfaces, and classes like in other programming languages. A generic function has type parameters listed in angle brackets:
function reverseAndMerge<T>(arr1: T[], arr2: T[]): T[] {
return arr1.reverse().concat(arr2.reverse());
}
let arr1: number[] = [1, 2, 3];
let arr2: number[] = [4, 5, 6];
let arr = reverseAndMerge(arr1, arr2);
Such generic functions can be defined with generic interfaces as well. The function signature for reverseAndMerge is compatible with the following generic interface:
interface GenericArrayFn<T> {
(arr1: T[], arr2: T[]): T[];
}
let arr: GenericArrayFn<number> = reverseAndMerge;
Note that the generic type parameter list in angle brackets follows the name of the function and interface. This is also true for classes:
class GenericValue<T> {
constructor(private value: T) { }
increment: (x: T) => T;
decrement: (x: T) => T;
}
let genericValue = new GenericValue<number>(5);
genericValue.increment = function (x) {return ++x;};
genericValue.decrement = function (x) {return --x;};
推薦閱讀
- 從零構(gòu)建知識(shí)圖譜:技術(shù)、方法與案例
- 嵌入式軟件系統(tǒng)測(cè)試:基于形式化方法的自動(dòng)化測(cè)試解決方案
- 測(cè)試驅(qū)動(dòng)開發(fā):入門、實(shí)戰(zhàn)與進(jìn)階
- Hands-On Data Structures and Algorithms with JavaScript
- Xcode 7 Essentials(Second Edition)
- Hands-On JavaScript High Performance
- HTML5入門經(jīng)典
- Apache Kafka Quick Start Guide
- Yii Project Blueprints
- Babylon.js Essentials
- Managing Microsoft Hybrid Clouds
- Python語言科研繪圖與學(xué)術(shù)圖表繪制從入門到精通
- Python計(jì)算機(jī)視覺和自然語言處理
- Practical Microservices
- 區(qū)塊鏈架構(gòu)之美:從比特幣、以太坊、超級(jí)賬本看區(qū)塊鏈架構(gòu)設(shè)計(jì)