Skip to content

How to Turn TypeScript Enums Into String Literal Types


Created: Dec 15, 2022 – Last Updated: Dec 15, 2022

Tags: TypeScript

Digital Garden

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 (opens in a new tab) and string literal type (opens in a new tab) in TypeScript:

ts
// Enum
enum Direction {
Up = "UP",
Down = "DOWN",
}
// String Literal Type
type Direction = "UP" | "DOWN"
// Example usage of enums
const 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:

shell
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 (opens in a new tab) to turn the Direction enum into a string literal type like this:

ts
enum Direction {
Up = "UP",
Down = "DOWN",
}
const example: YourType = [
/* Contents */
]
// The `${Direction}` is the important piece here
type 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"

Want to learn more? Browse my Digital Garden