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

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 
 
Note that the data type to be processed is passed by wrapping it in angle brackets (<>) in the function call.
主站蜘蛛池模板: 平塘县| 公主岭市| 北川| 光山县| 镇雄县| 神木县| 富平县| 台东市| 图木舒克市| 新巴尔虎左旗| 井冈山市| 马鞍山市| 仙居县| 滁州市| 柳林县| 平安县| 茌平县| 建德市| 都安| 上林县| 乾安县| 泰州市| 弥渡县| 吉首市| 左权县| 安陆市| 徐水县| 荥经县| 长海县| 长武县| 永定县| 龙陵县| 高尔夫| 云梦县| 安乡县| 商南县| 凤冈县| 麟游县| 达尔| 五峰| 江陵县|