Languages
[Edit]
EN

TypeScript - generic types

10 points
Created by:
Root-ssh
177780

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...
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join