EN
TypeScript - generic types
10
points
In TypeScript it is possible to work with generic types in following ways.
1. generic function example
function print<T>(value : T) : void {
console.log(value);
}
function power<T extends number>(value : T) : void {
let result = Math.pow(value, 2);
console.log(result);
}
print('text');
print<string>('text');
power(4);
power<number>(4);
Output:
text
text
16
16
2. generic class example
class Utils<V extends number> {
public print<T>(object : T) : void {
console.log(object);
}
public power(value : V) : void {
let result = Math.pow(value, 2);
this.print(result);
}
public multiply(value : V) : void {
let result = 2 * value;
this.print(result);
}
}
let utils = new Utils<number>();
utils.print('Results:');
utils.power(4);
utils.power<number>(4);
utils.multiply(5);
utils.multiply<number>(5);
utils.print('Finished!');
Output:
Results:
16
16
10
10
Finished!
3. generic interface example
interface IInstrument<T> {
getName() : string;
getData() : T;
playSong() : void;
}
class Drum implements IInstrument<string> {
public getName() : string {
return 'Drum';
}
public getData() : string {
return 'This is instruction how to play melody with drums...';
}
public playSong() : void {
console.log('This is drum song...');
}
}
let drum = new Drum();
console.log(`Name: ${drum.getName()}`);
console.log(`Data: ${drum.getData()}`);
drum.playSong();
Output:
Name: Drum
Data: This is instruction how to play melody with drums...
This is drum song...