Objects 16 exercises
Problem

Allow Dynamic Keys in TypeScript Types

Here we have an object called scores, and we are trying to assign several different properties to it:


const scores = {};
scores.math = 95; // red squiggly line under math
scores.english = 90; // red squiggly line under english
scores.science = 85; // red squiggly line under science

Loading exercise

Transcript

00:00 In this exercise, we have an object called Scores here, and we are trying to assign into Scores, this Scores object, a bunch of different properties, Math, English and Science, all with different numbers. Your job is to work out how we can strongly type Scores.

00:16 Now, this is a little bit non-trivial because we don't just want to be able to add Math, English and Science into Scores. This is kind of acting like a dictionary. We want to be able to add any random kind of thing we want to into Scores. So we don't have the ability to predict ahead of time what subjects are going to be added in there.

00:37 So your job is to try to figure out the best way to type Scores so that we can add anything into it, any kind of key that is a string. There are about four different solutions to this.

00:49 So don't worry if you don't get all of them, but see if you can find a way to type Scores without changing any of the code down here or changing any of the runtime code to make these errors go away. Good luck.