-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgenerics.ts
53 lines (39 loc) · 1.15 KB
/
generics.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function identity(arg: number): number {
return arg;
}
function identity2(arg: any): any {
return arg;
}
function identity3<T>(arg: T): T {
return arg;
}
let output = identity3<string>('Hola');
let output1 = identity3(10);
let output2 = identity3('10');
let output3 = identity3(true);
//////////////////////////////////////////////////////////////////////////////
function loggingIdentity<T>(arg: T): T {
console.log(arg.length); // Error: T doesn't have .length
return arg;
}
function loggingIdentity2<T>(arg: T[]): T[] {
console.log(arg.length); // Array has a .length, so no more error
return arg;
}
//////////////////////////////////////////////////////////////////////////////
interface GenericIdentityFn {
<T>(arg: T): T;
}
function identity4<T>(arg: T): T {
return arg;
}
let myIdentity: GenericIdentityFn = identity4;
//////////////////////////////////////////////////////////////////////////////
// we now will also need to specify the corresponding type argument (here: number)
interface GenericIdentityFn2<T> {
(arg: T): T;
}
function identity5<T>(arg: T): T {
return arg;
}
let myIdentity2: GenericIdentityFn2<number> = identity5;