EN
TypeScript - generic types
10 points
In TypeScript it is possible to work with generic types in following ways.
xxxxxxxxxx
1
function print<T>(value : T) : void {
2
console.log(value);
3
}
4
5
function power<T extends number>(value : T) : void {
6
let result = Math.pow(value, 2);
7
8
console.log(result);
9
}
10
11
print('text');
12
print<string>('text');
13
power(4);
14
power<number>(4);
Output:
xxxxxxxxxx
1
text
2
text
3
16
4
16
xxxxxxxxxx
1
2
class Utils<V extends number> {
3
public print<T>(object : T) : void {
4
console.log(object);
5
}
6
7
public power(value : V) : void {
8
let result = Math.pow(value, 2);
9
10
this.print(result);
11
}
12
13
public multiply(value : V) : void {
14
let result = 2 * value;
15
16
this.print(result);
17
}
18
}
19
20
let utils = new Utils<number>();
21
22
utils.print('Results:');
23
utils.power(4);
24
utils.power<number>(4);
25
utils.multiply(5);
26
utils.multiply<number>(5);
27
utils.print('Finished!');
Output:
xxxxxxxxxx
1
Results:
2
16
3
16
4
10
5
10
6
Finished!
xxxxxxxxxx
1
interface IInstrument<T> {
2
getName() : string;
3
getData() : T;
4
playSong() : void;
5
}
6
7
class Drum implements IInstrument<string> {
8
public getName() : string {
9
return 'Drum';
10
}
11
12
public getData() : string {
13
return 'This is instruction how to play melody with drums...';
14
}
15
16
public playSong() : void {
17
console.log('This is drum song...');
18
}
19
}
20
21
let drum = new Drum();
22
23
console.log(`Name: ${drum.getName()}`);
24
console.log(`Data: ${drum.getData()}`);
25
26
drum.playSong();
Output:
xxxxxxxxxx
1
Name: Drum
2
Data: This is instruction how to play melody with drums...
3
This is drum song...