Type | Treat Challenge 5
Gabrielle Crevecoeur
Posted on October 30, 2020
Welcome to the final Type | Treat challenge! Today we will be restocking Halloween candy and identifying Halloween movies
Yesterday's Solution
Beginner/Learner Challenge
We were looking for using the Readonly
utility type to force the type to not allow poltergeists to make changes to your rooms.
- type Rectory = {
+ type Rectory = Readonly<{
rooms: Room[]
noises: any[]
- }
+ }>
- type Room = {
+ type Room = Readonly<{
name: string
doors: number
windows: number
ghost?: any
- }
+ }>
It's worth remembering that JavaScript doesn't have immutability like this, so this really only affects the type system. You'll get a compiler error, but people can still work around that.
Intermediate/Advanced Challenge
This challenge evolved quite naturally from the third challenge with the addition of 4.1's heading feature Template Literals.
The most elegant answer moved the return type into the object const winners
which would then be inferred as the return type of tallyPopularWinners
:
const breeds = ["Hound" , "Corgi" , "Pomeranian"] as const
const costumes = ["Pumpkin" , "Hot Dog" , "Bumble Bee"] as const
+ type Breed = typeof breeds[number]
+ type Costume = typeof costumes[number]
+ type BreedCostumeCombination = `${lowercase typeof breeds[number]}-${lowercase typeof costumes[number]}`
function tallyPopularWinners(_breeds: typeof breeds, _costumes: typeof costumes) {
- const winners = {} as any
+ const winners: Record<BreedCostumeCombination, ReturnType<typeof decideWinner>> = {} as any
Our answer Also, we watched the full two hours of that video, and it's a great background video while you're working.
The Challenge
Beginner/Learner Challenge
You're in charge of restocking the houses on your street, can you find a way to reduce the duplication in your notes by generically declaring a house?
Intermediate/Advanced Challenge
You're working on a horror movie night. You've skipped the types because you figured it'd be simple to work with but someone put the wrong movie in and The Nightmare Before Christmas is not a halloween movie. It's in the name. Anyway. To avoid this happening again, you figure it's time to add types to the function. Once, you got that down then you wonder if you can do the same thing for the kids schedule?
Share
Be sure to submit your solution by using the Share button in the TypeScript playground.
Then go to Twitter, and create a tweet about the challenge, add the link to your code and mention the TypeScript page (@typescript)
Need Extra Help?
If you need additional help you can utilize the following:
- The TypeScript Handbook
- TypeScript Discord Page
- The comments on each Dev.to posts!
Happy Typing :)
Posted on October 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.