Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

TypeScript - generic types

0 contributions
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...

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more