Objects 16 exercises
solution

Add an Index Signature to an Interface

There are a couple of ways to solve this problem.

Using an Index Signature

The first way we'll look at is adding an index signature to our Scores interface.

In this case, we'll call the index signature subject, and specify that it should have numerical values. Then we'll add the default `m

Loading solution

Transcript

00:00 Okay, let's do it The main thing is we want to add our index signature first So we have subject which is going to be a number or no Sorry string and then the value is going to be number But then we've still got the error up here saying science is missing and we should be able to just add math

00:16 Number English number and science number just below it. Look at that. How cool is that? Now we're gonna get an error here saying property science is missing in that type So we get autocomplete for science and everything is great So you can see here that sure we've got our index signature here

00:33 But that doesn't mean we can't just add other properties onto this but they have to correspond to that index signature So math here is typed as a string But it's got to be assignable to this type here So the number type we could make this more specific so we could say this has to be a specific number

00:52 so in this case 95 down below but This isn't right for this use case because we should be able to represent that people can get anything other than high math scores So this is one way to do it. Another way you can do it is with Predefined keys like this. Sorry with interface extends. So we have interface scores extends required scores

01:13 So this is kind of like combining two different pieces together And of course if we go back to the other one, we can just change these two types as well This is perfectly possible inside a type. So this isn't just an interface feature. It's also a type feature. So there you go This is how you implement index signatures with predefined keys kind of that are required by default