Skip to content

Instantly share code, notes, and snippets.

@Nachasic
Last active February 10, 2019 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nachasic/bbb1b4a739c8b413a06e88f37ac7d465 to your computer and use it in GitHub Desktop.
Save Nachasic/bbb1b4a739c8b413a06e88f37ac7d465 to your computer and use it in GitHub Desktop.
Exemplary explanation of interfaces and generics
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