Collect Related Strings in a String Enum in TypeScript

Share this video with your friends

Send Tweet

As of TypeScript 2.4, it is now possible to define string enums, or more precisely, enums with string members. Just like any other numeric enum, string enums can be made constant using the const modifier so that they disappear entirely from the generated JavaScript; in this case, all enum values will be inlined into the output.

Stephen
Stephen
~ 7 years ago

Its seems that 'fetch' under ts 2.5.3 has no correct typings, so there are several warnings with headers etc. Great lessons here, but can no longer code along.

Marius Schulz
Marius Schulz(instructor)
~ 7 years ago

@Stephen: Yeah, this is currently a known regression, but the fix has been merged already, so it should be part of the next TypeScript release.

Brendan Whiting
Brendan Whiting
~ 7 years ago

What’s the advantage of string enum over a union type of string literals?

enum ReservationType {
  PICKUP = ‘PICKUP,
  DROPOFF = 'DROPOFF'
}

type ReservationType = "PICKUP" | "DROPOFF";
Marius Schulz
Marius Schulz(instructor)
~ 7 years ago

@Brendan: String enums and string literal types compile to different JavaScript code. String enums typically emit a mapping object (unless you use a const enum without --preserveConstEnums), whereas string literal types have no runtime manifestation at all.

If you're typing an existing JavaScript API, you'd probably use string literal types to describe the set of allowed values. In your own applications, you can use either string enums and string literal types, whichever one you prefer.

Brendan Whiting
Brendan Whiting
~ 7 years ago

Cool, thanks