Designing Your Types 11 exercises

Derive Types with Mapped Types

Here we have an Attributes interface, that contains a firstName, lastName, and age:

interface Attributes {
firstName: string;
lastName: string;
age: number;

Following that, we have AttributeGetters which is currently typed as unknown:

type AttributeGetters =

Loading exercise


00:00 In this exercise, we're going to look at mapped types in TypeScript. We have here an interface attributes, and attributes has a first name, last name, which are strings, and then age, which is a number. Then down here, we have attribute getters, which is currently typed as unknown. Then down in the tests, we have expect equal attribute getters,

00:19 and we're expecting that to be an object of functions, where we basically grab the first name and it's going to be a string. So it's going to be dot first name, call that, and then you get a string from the end of it. And this is a hard problem because we need this attribute getters

00:37 to be derived from this interface attributes. And in order to do that, we're going to map over each one of those keys, and then create on the value, a function which returns the key of that value. We're going to need mapped types for this. I will include a link below.

00:55 And this is a tricky problem, but you're going to see how powerful it is in transforming objects from one shape to another.