- Hands-On Full Stack Web Development with Angular 6 and Laravel 5
- Fernando Monteiro
- 261字
- 2021-07-23 19:18:51
Creating generic functions
Generics are a very useful way of creating flexible classes and functions. They are very similar to those used in C#. It's very useful to be used in more than one place.
We can create generic functions by adding angle brackets after the function names and enclosing datatypes, as in the following example:
function genericFunction<T>( arg: T ): T [] {
let myGenericArray: T[] = [];
myGenericArray.push(arg);
return myGenericArray;
}
Note that the t inside the angle brackets (<t>) means that genericFunction() is of the generic type.
Let's see this in practice:
- In your code editor, create a new file called generics.ts, and add the following code:
function genericFunction<T>( arg: T ): T [] {
let myGenericArray: T[] = [];
myGenericArray.push(arg);
return myGenericArray;
}
let stringFromGenericFunction = genericFunction<string>("Some string goes here");
console.log(stringFromGenericFunction[0]);
let numberFromGenericFunction = genericFunction(190);
console.log(numberFromGenericFunction[0]);
Let's see what happens with our generic function.
- Go back to your Terminal and type the following command:
tsc generics.ts
- Now, let's execute the file with the following command:
node generics.js
We will see the following result:
Some string goes here
190
Note that the compiler is able to identify the datatype that we are passing as the function argument. In the first case, we explicitly pass the argument as a string, and in the second case, we pass nothing.
Although the compiler is able to identify the type of argument that we are using, it is important to always determine what kind of data we are going to pass. For example:
let numberFromGenericFunction = genericFunction<number>(190);
console.log(numberFromGenericFunction[0]);
- 解析QUIC/HTTP3:未來互聯網的基石
- Application Development with Qt Creator(Second Edition)
- 數據通信網絡實踐:基礎知識與交換機技術
- HTML5 Game development with ImpactJS
- 互聯網安全的40個智慧洞見:2014年中國互聯網安全大會文集
- Metasploit Penetration Testing Cookbook
- Kong網關:入門、實戰與進階
- SAE原理與網絡規劃
- Master Apache JMeter:From Load Testing to DevOps
- TD-LTE無線網絡規劃與設計
- 計算機網絡技術
- 物聯網技術與實踐
- ReasonML Quick Start Guide
- ElasticSearch Server
- 網絡分析技術揭秘:原理、實踐與WinPcap深入解析