Created
May 31, 2022 22:31
-
-
Save squarism/3799d42b4187434b06325ce1c08a5478 to your computer and use it in GitHub Desktop.
Typescript Enums and Types 03
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
type AnimalToPet = { | |
kind: string | |
target: CalicoCat | SphynxCat | Turtle | |
} | |
type Animal = { | |
appearance: string | |
} | |
type CalicoCat = Animal & { | |
onlyACalicoThing: string | |
} | |
type SphynxCat = Animal & { | |
onlyASphynxThing: string | |
} | |
type Turtle = Animal & {} | |
const petCat = function(animal: AnimalToPet) { | |
console.log("What kind of cat am I petting?") | |
// new in TS4.6 | |
const { kind, target } = animal; | |
if (kind === "Turtle") { | |
console.log("This is not a Cat at all!") | |
} else { | |
console.log(target.appearance) | |
} | |
} | |
const calico: CalicoCat = { | |
appearance: "Looks like a CalicoCat.", | |
onlyACalicoThing: "being orange and stripey" | |
} | |
const sphynx: SphynxCat = { | |
appearance: "Looks like a SphynxCat.", | |
onlyASphynxThing: "doing sphynx stuff" | |
} | |
// this is still strings for classes | |
petCat({ kind: "CalicoCat", target: calico }); | |
petCat({ kind: "SphynxCat", target: sphynx }); | |
petCat({ kind: "Turtle", target: { appearance: "???" } }); | |
// [LOG]: "What kind of cat am I petting?" | |
// [LOG]: "Looks like a CalicoCat." | |
// [LOG]: "What kind of cat am I petting?" | |
// [LOG]: "Looks like a SphynxCat." | |
// [LOG]: "What kind of cat am I petting?" | |
// [LOG]: "This is not a Cat at all!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment