Last active
April 2, 2025 15:38
-
-
Save MarwanShehata/b90d14fa48c0ed5c5f316012f8385509 to your computer and use it in GitHub Desktop.
This ensures that if a new kind is added to the Animals type and isn't handled in the switch, TypeScript will catch it as a type error at compile time. π
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 `never` is great for exhaustive checking, great for exhaustive switch statements | |
type Bird = { | |
kind: 'bird' | |
legs: number | |
wings: 2 | |
} | |
type Dog = { | |
kind: 'dog' | |
legs: number | |
} | |
type Fish = { | |
kind: 'fish' | |
fins: number | |
} | |
type Animals = Bird | Dog | Fish | |
function AnimalAppendages(animal: Animals) { | |
switch (animal.kind) { | |
case 'bird': | |
return animal.legs + animal.wings | |
case 'dog': | |
return animal.legs | |
case 'fish': | |
return animal.fins | |
break | |
default: | |
// Exhaustiveness check: If `animal` is ever an unhandled case, TypeScript will throw an error. | |
let _: never = animal | |
return _ | |
break | |
} | |
} | |
type CurrencyOptions = 'EGP' | 'USD' | 'EUR' | |
function getRate(rate: CurrencyOptions) { | |
switch (rate) { | |
case 'EGP': | |
return 50 | |
case 'USD': | |
return 1 | |
case 'EUR': | |
return 1.3 | |
default: | |
let _: never = rate | |
return _ | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment