Deriving Types From Values 15 exercises
explainer

Enums as Types and Values in TypeScript

Consider this LogLevel enum with four levels: Debug, Info, Warn, and Error.


enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3,
}

We also have a log function that takes in a level parameter of type LogLevel:


function log(opts: {
globalLog

Loading explainer

Transcript

00:00 Classes can cross the type and value barrier, and so can enums. So this enum, we have a log level here, which has debug, info, warn, and error, which we've seen before. And we have our function log here. When we declare inside global log level that it's a log level,

00:16 we don't need to do type of log level or anything like that. And we can just say log level and use it as its type there. So again, these kind of TypeScript features that were added early on, they do have quite nice DX, you know, you can just use them as a value or a type without having to do a type of transformation between them.

00:36 And that's pretty nice. So using this log level and this level here, we can just get a really nice API, even if, of course, these still have the traditional benefits or traditional drawbacks of enums, which is you have to import them and have to do all that stuff. So, interesting.