How to Turn TypeScript Enums into String Literal Types
Recently I was stuck on a TypeScript problem involving enums and how to turn those into a string literal type. I was working on public TypeScript types for a project which internally used enums. In this instance I wanted the external users to not have to import enums but have string literal types. This way they should get intellisense automatically.
So, to get on the same page, here’s an example of an enum and string literal type in TypeScript:
// Enumenum Direction { Up = "UP", Down = "DOWN",}
// String Literal Typetype Direction = "UP" | "DOWN"
// Example usage of enumsconst example = [ { direction: Direction.Up, }, { direction: Direction.Down, },]
The example
array of objects will have a TypeScript type of Array<{ direction: Direction }>
. But if you’d turn that into a public TypeScript type and your users would use direction: "UP"
, TypeScript would complain with:
Type '"UP"' is not assignable to type 'Direction'.
They’d need to import the Direction
enum and use it.
You can use template literal types to turn the Direction
enum into a string literal type like this:
enum Direction { Up = "UP", Down = "DOWN",}
const example: YourType = [ /* Contents */]
// The `${Direction}` is the important piece heretype YourType = Array<{ direction: `${Direction}` }>
So with the same syntax as template literal strings you turn an enum into a string literal type! With this you can still internally use enums but your users will get intellisense like this now while filling out the array of objects:
(property) direction: "UP" | "DOWN"