Last active
February 10, 2019 18:36
-
-
Save Nachasic/bbb1b4a739c8b413a06e88f37ac7d465 to your computer and use it in GitHub Desktop.
Exemplary explanation of interfaces and generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface BarkAndWiggle { | |
bark: () => void; | |
wiggle: () => void; | |
}; | |
class Pitbull implements BarkAndWiggle { | |
public bark() { | |
console.log('bark'); | |
} | |
public wiggle() { | |
console.log('happy'); | |
} | |
} | |
class Pug implements BarkAndWiggle { | |
public bark() { | |
console.log('yaff'); | |
} | |
public wiggle() { | |
console.log('tiny happy'); | |
} | |
} | |
const buck: Pitbull = new Pitbull(); | |
const frank: Pug = new Pug(); | |
function MakeBarkAndReturn<T extends BarkAndWiggle> (animal: T): T { | |
animal.bark(); | |
return animal; | |
} | |
const someAnimal = MakeBarkAndReturn(frank); // someAnimas is of type 'Pug' | |
const foo: Array<string> = ['foo', 'bar']; | |
const pets = new Array<BarkAndWiggle>(frank, buck); | |
class Alien<T extends BarkAndWiggle> { | |
private foodInStomach: T; | |
public eat(food: T) { | |
this.foodInStomach = food; | |
} | |
public pokeBelly(): T { | |
this.foodInStomach.bark(); | |
return this.foodInStomach; | |
} | |
} | |
const zargon = new Alien<Pitbull>(); | |
zargon.eat(frank); // ERROR wrong type of food | |
zargon.eat(buck); // Ok, edible | |
const result = zargon.pokeBelly(); // outputs 'bark', result is of type 'Pitbull' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment