The Challenge
Let’s get some hands on experience working with template literal types by building a data store, whose method names are based on the type of entities we’re managing.
If you look at the starting point code for this exercise, you’ll see the following
tsTry
export interfaceDataEntity {id : string}export interfaceMovie extendsDataEntity {director : string}export interfaceSong extendsDataEntity {singer : string}export typeDataEntityMap = {movie :Movie song :Song }export classDataStore {}
This DataEntityMap
object should drive a lot of what happens to DataStore
.
Ultimately, DataStore
should end up with methods like
ts
const ds = new DataStore()ds.addSong({ id: "song-123", singer: "The Flaming Lips" })ds.addMovie({id: "movie-456",director: "Stephen Spielberg",})ds.getSong("song-123") // returns the songds.getMovie("movie-456") // returns the movieds.getAllSongs() // array of all songsds.getAllMovies() // array of all moviesds.clearSongs() // clears all songsds.clearMovies() // clears all movies
It’s ok to define these explicitly in the DataStore
class, but they should be
type-checked against the DataEntityMap
type in some way.
Requirements
- If you mis-name a method on the class (e.g.,
getSongs
instead ofgetAllSongs
), you should get some sort of type error that alerts you that you’ve broken the established pattern - If you add a new entity like
Comic
(shown below) and make no other changes to your solution, you should get some sort of type error that alerts you to the absence of aclearComics
,getAllComics
andgetAllSongs
method.
diff
+export interface Comic extends DataEntity {+ issueNumber: number+}export type DataEntityMap = {movie: Moviesong: Song+ comic: Comic}
- There should be no externally-visible properties on an instance of
DataStore
beyond the required methods - Your code, and the test suite should type-check
- All pre-existing tests should pass
Setup
First, if you haven’t done so already, clone the workshop project for this course
sh
git clone https://github.com/mike-north/making-typescript-stickcd making-typescript-stick
Make sure you have Volta installed. If you haven’t done so already, just run the following to install it
sh
curl https://get.volta.sh | bash
Next, let’s install our dependencies
sh
yarn
and finally, let’s navigate to the folder containing this specific challenge
sh
cd challenges/data-layer
You can now run the test suite by running yarn test
Your job is to modify the code in ./src/index.ts
until all of the requirements of this exercise are met
Hints
- Brush up on indexed access types
- Brush up on mapped types, and in particular the new “key remapping” feature that landed in TS 4.1
- Brush up on template literal types