Dynamically Typed Contract - TypeScript Challenge 01
Quite a while ago, I did TypeScript Challenges from Ant Fu, and if you are unfamiliar with it, I strongly suggest you check it out. Since then, I've been looking for more challenges to improve my TypeScript knowledge, but finding the ones we can use in real-world applications is hard.
I present you with some challenges I found and believe are helpful in real projects. This post is challenge #1, and I'll keep posting more editions of these.
Challenge
Let's build a Store
class that should be able to get
, getAll
, add
and clear
some songs and movies. You're presented with the initial types and you have to build the class functionality, as well as attempt to make it dynamically typed.
This is your starting point
export interface CommonData {
id: number
title: string
}
export interface Movie extends CommonData {
director: string
}
export interface Song extends CommonData {
artist: string
}
export type Entities = {
movie: Movie
song: Song
}
export class Store {}
Ultimately, we want to have a class that will be able to handle the following actions:
const store = new Store()
store.addSong({ id: 873, artist: 'Wiz Khalifa', title: 'No Limit' })
store.getSong(873)
store.getAllSongs()
store.clearSongs()
store.addMovie({
id: 23,
director: 'Francis Ford Coppola',
title: 'The Godfather',
})
store.getMovie(23)
store.getAllMovies()
store.clearMovies()
If you are too lazy to copy the starting point, here's a TS Playground ready for you to tackle. This challenge may be easy, but I dare you to try your best and look at the solution afterward.
Requirements
- If you type incorrect name of an method (e.g.
getSongs
instead ofgetAllSongs
), you should get a type error; alerting you that you've broken defined pattern - If you add a new property to the
Entities
type (e.g.{ comic: Comic }
) and no further changes to the class itself, you should get a type error; alerting you of absence from all required methods - There shouldn't be externally visible and accessible properties on an instance of the class
Hints
Solution
As I do not have interactive sandbox implementation on my website yet, I am providing a link to TS Playground - solution, where you can modify or copy the completed challenge for later use or learning purposes.