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

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.
主站蜘蛛池模板: 陆川县| 雅安市| 上饶县| 大丰市| 定兴县| 申扎县| 丰城市| 巴马| 浦城县| 喀喇| 中阳县| 株洲县| 田林县| 乌恰县| 灌南县| 鹤庆县| 潼关县| 徐水县| 赣榆县| 台州市| 宜阳县| 海南省| 阿图什市| 遂川县| 青冈县| 涿鹿县| 宣武区| 柳州市| 石首市| 阳信县| 平远县| 舞钢市| 阜新市| 康保县| 赤水市| 娄底市| 涡阳县| 介休市| 民丰县| 石景山区| 阳朔县|