Skip to content

Instantly share code, notes, and snippets.

@neelabhg
Created December 25, 2021 17:00
Show Gist options
  • Save neelabhg/635c2e6d177b3bae69ce838793a6451c to your computer and use it in GitHub Desktop.
Save neelabhg/635c2e6d177b3bae69ce838793a6451c to your computer and use it in GitHub Desktop.
Type Variance Example
interface Animal {
name: string;
}
interface Cat extends Animal {
meow: () => void;
}
function doMeow(cat: Cat) {
cat.meow();
}
function sayName(a: Animal) {
console.log(a.name);
}
const cat: Cat = {
name: "Sir cat",
meow: () => console.log("Meow!")
}
doMeow(cat)
function handleCat(cat: Cat, callback: (a: Cat) => void) {
callback(cat);
}
function handleAnimal(cat: Cat, callback: (a: Animal) => void) {
callback(cat);
}
handleCat(cat, doMeow);
handleCat(cat, sayName);
handleAnimal(cat, doMeow);
handleAnimal(cat, sayName);