TypeScript Only Features 9 exercises
Problem

Working with Enums in TypeScript

In this exercise, we are working with a log function.

The log function takes in an options object with three properties: globalLogLevel, level, and message:


function log (opts: {
globalLogLevel: number;
level: number;
message: string;
}) => {
if (opts.level >= opts.

Loading exercise

Transcript

00:00 In this exercise, we're going to look at enums. To do that, we have a function called log. A log takes in an object with three members of that, or three properties on that object. It has global log level, which is a number, level, which is a number, and message, which is a string. Now, we have a const log level up at the top here

00:19 with debug, which is zero, info, one, one, two, and error, three, a kind of rising set of kind of log levels, essentially, where debug is the lowest and error is the highest. So you can imagine that if you have a global log level set within your application, then you should be able to only see errors

00:38 of that kind of magnitude or higher, of that level or higher. So if we set it to debug, then we're going to get all the messages. If we set it to warn, then we'll only get the warnings. You get the idea, and warnings and errors, et cetera. So we've got some various functions where like it's checking that should log

00:57 of the level is equal to the global log level, but we've also got an error down the bottom, which is saying should give you a TypeScript error if you pass in an invalid log level. And this is currently the only thing that's failing about this whole situation. We're using log level dot as like the, it's kind of like a sort of enum from other languages that you might have seen

01:16 where we're kind of using log level as the sort of central point that decides what all of these levels are. And your job is to try to figure out a better way to first of all, like express this log level and also express the types that come inside these options here. I don't think you should need to change

01:35 any of the other pieces of code here. And for this solution, you will need to use an enum and the enum keyword in TypeScript is available to you. Good luck.