Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTypeScript

String unions vs enums vs as const objects

Use a string union for type checking and derive it from an as const object when you also need the values at runtime.

You declared a string enum for user roles. A test then passes 'admin' to a function that takes a Role, and the compiler refuses it.

enum Role {
  Admin = 'admin',
  Editor = 'editor',
}

function canPublish(role: Role) {
  return role === Role.Admin || role === Role.Editor
}

canPublish(Role.Admin)
canPublish('admin')
// error TS2345: Argument of type '"admin"' is not assignable to parameter of type 'Role'.

TypeScript accepts Role.Admin and rejects the plain string 'admin' at this call site. When a value arrives as JSON, validate it before treating it as a Role.

This string enum also emits code that builds the Role object when the module loads.

Keep the values, derive the type

If you need the values at runtime, to fill a select or validate input, write the object first and take the type from it.

const ROLES = {
  Admin: 'admin',
  Editor: 'editor',
} as const

type Role = (typeof ROLES)[keyof typeof ROLES]

function canPublish(role: Role) {
  return role === ROLES.Admin || role === ROLES.Editor
}

canPublish(ROLES.Admin)
canPublish('admin')
canPublish('owner')
// error TS2345: Argument of type '"owner"' is not assignable to parameter of type 'Role'.

as const keeps each value as the literal 'admin' instead of widening it to string. Read the type from the inside out. typeof ROLES is the object's type, keyof of that is 'Admin' | 'Editor', and indexing with those keys gives 'admin' | 'editor'.

canPublish('admin') compiles now and canPublish('owner') does not. Object.values(ROLES) prints [ 'admin', 'editor' ], and adding a key to ROLES widens Role with no second edit.

Skip the object when nothing reads it

If the values only exist to be checked, the union is the whole answer.

type Direction = 'left' | 'right'

function move(direction: Direction) {
  return direction === 'left' ? -1 : 1
}

move('left')
move('up')
// error TS2345: Argument of type '"up"' is not assignable to parameter of type 'Direction'.

Nothing is emitted for a type alias, so the union costs no bytes at runtime and 'left' is accepted anywhere a Direction is.

I start with the union. The day I need to loop over the values, I move them into an as const object and replace the union with the derived type. Call sites keep compiling because the type has the same members.