The Weird Parts of TypeScript 13 exercises

Iterating Over Object Keys in TypeScript

Consider an interface User with properties id and name:

interface User {
id: number;
name: string;

We have the skeleton of a printUser function that accepts a User as its argument:

function printUser(user: User) {}

Inside a test setup, we want

Loading exercise


00:00 In this exercise, we're going to look at iterating over object keys, navigating around the painful points of object.keys. So here we have an interface user, which has an ID and name. And we're expecting that when we call the printUser function with an ID of 1 and name of vacas,

00:16 that this console.log.spy, we're spying on console.log here, should have first been called with 1 and then it should be called with vacas. So of course, we could do this, we could say console.log and then console.log And then the tests will be passing here. So it's logged all the keys of the user. Fantastic.

00:36 And if I remove one of these, then it's going to error at me because I've not logged name. There we go. So, but we want to do this using a loop because let's imagine that the user has a bunch of different properties that we want to log all of them. Your job is to try to figure out how to best write this printUser function to take advantage of that.

00:55 And you're going to first of all need to either use a for loop or use object.keys for each. And you're also going to need to navigate some of the typing stuff here because if we remember object.keys is loosely typed or rather it's typed to always return an array of strings. Good luck.