Created
December 25, 2021 17:00
-
-
Save neelabhg/635c2e6d177b3bae69ce838793a6451c to your computer and use it in GitHub Desktop.
Type Variance Example
This file contains 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 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TS Playground link:
https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgIImAWzgG2QbwFgAoZZEOTCALmQGcwpQBzAbhIF8STRJZEUAYThhkEAB6QQAEzpoM2PEVLIqAewDutABQBKZAF4AfMgBua4NPbEuxEjACuIBGGBqQyaWoCyETdoQRWmEwfWUyQLAAOnUNPWtbeycXNw86OABPADlKCG04WnQsXDCSCPc6NRwIKJw1ZnyoiipdBO5iBArRSOCRQwIy8lzaACIAZWAoZEiRgBpB2J19Y2mKqpq6hpHfTQBCEd1Odq8duMjDu2JHZ1d3ZAALOBlqkICg5BDZ6dwcACNEADWOgKHxEyxM5kspRUgRwf0Bb1CbUu1xSd0ezwgRUUiN6YC+sPhCCByHyhQUJUMEIs0mhER+-2JiNaR0uGOkLxEiK+Jz8GhZxHZnLA3PomRyLWsJCFWIpOFFvM0Apl2NwovS2VyAqAA