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
tsTryexport 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
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., getSongsinstead 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,getAllComicsandgetAllSongsmethod.
diff
- There should be no externally-visible properties on an instance of DataStorebeyond 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
Make sure you have Volta installed. If you haven’t done so already, just run the following to install it
sh
Next, let’s install our dependencies
sh
and finally, let’s navigate to the folder containing this specific challenge
sh
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