官术网_书友最值得收藏!

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:

  1. 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.

  1. Go back to your Terminal and type the following command:
tsc generics.ts
  1. 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]);
主站蜘蛛池模板: 博乐市| 利辛县| 连州市| 光山县| 鹰潭市| 清苑县| 疏勒县| 岳阳市| 乌拉特中旗| 修武县| 古浪县| 龙川县| 会东县| 高邮市| 尚义县| 阿鲁科尔沁旗| 宜君县| 简阳市| 平舆县| 漳州市| 安远县| 韶关市| 巴塘县| 湘潭市| 鹤峰县| 福州市| 瓮安县| 襄城县| 海城市| 岳池县| 玛多县| 大名县| 体育| 龙门县| 阿坝| 永昌县| 克东县| 朝阳市| 八宿县| 灵山县| 左云县|