Sub topic 5
Deriving Union Types from Values
This chapter assumes you know basic TypeScript types, let versus const, union types, literal types, and typeof and keyof in type positions. It also assumes you have seen as const. The goal is to make one runtime value the source of truth for both your program data and a TypeScript union.
Why derive a union from a value?
Suppose an application accepts three roles:
type Role = "admin" | "editor" | "viewer";This type protects function calls and object properties:
function canDelete(role: Role): boolean {
return role === "admin";
}
canDelete("admin"); // OK
// canDelete("owner"); // ErrorHowever, the application may also need the roles at runtime:
const ROLES = ["admin", "editor", "viewer"];Now the same information appears twice:
type Role = "admin" | "editor" | "viewer";
const ROLES = ["admin", "editor", "viewer"];These two declarations can become inconsistent. If you add "owner" to one but not the other, the compiler cannot generally detect the mistake.
A const array with as const lets you derive the union from the runtime value:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
// "admin" | "editor" | "viewer"The array is the source of truth. Its values are available at runtime, and its type provides the Role union.
How indexed access creates the union
The expression has three parts:
type Role = (typeof ROLES)[number];typeof ROLESgets the type of the valueROLES.[number]indexes every numeric position in that array type.- The result is the union of the element types.
Because as const creates a readonly tuple, TypeScript sees this type:
readonly ["admin", "editor", "viewer"]Indexing that tuple with number means “give me the type at any valid numeric position.” The result is:
"admin" | "editor" | "viewer"You can inspect the relationship in a complete example:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
function describeRole(role: Role): string {
switch (role) {
case "admin":
return "Can manage the application";
case "editor":
return "Can edit content";
case "viewer":
return "Can read content";
}
}
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value);
}
console.log(describeRole("editor"));
const input = "viewer";
if (isRole(input)) {
console.log(describeRole(input));
}The isRole function checks an arbitrary string at runtime. Its return type, value is Role, tells TypeScript that value has been narrowed to Role when the function returns true.
The array must stay narrow
Without as const, the array elements widen:
const ROLES = ["admin", "editor", "viewer"];
type Role = (typeof ROLES)[number];
// stringThe inferred array type is string[], so indexing it produces string, not the desired literal union.
With as const, each element keeps its literal type:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
// "admin" | "editor" | "viewer"This pattern works for any literal values:
const RETRY_DELAYS = [100, 500, 1000] as const;
type RetryDelay = (typeof RETRY_DELAYS)[number];
// 100 | 500 | 1000A common error is to assume that const alone is enough. const prevents reassignment of the variable, but it does not always preserve literal element types inside an array. as const supplies the required narrow, readonly tuple type.
Deriving unions from objects
Objects are useful when each value needs a meaningful name:
const Status = {
Active: "active",
Archived: "archived",
Pending: "pending",
} as const;To derive the union of the values, first get the object type, then get its keys, then index that type by those keys:
type Status = (typeof Status)[keyof typeof Status];
// "active" | "archived" | "pending"Read this from the inside out:
typeof Statusis the type of the object value.keyof typeof Statusis"Active" | "Archived" | "Pending".- Indexing the object type with those keys returns the value types.
The type and value can intentionally share the name Status because TypeScript keeps value names and type names in separate namespaces:
const Status = {
Active: "active",
Archived: "archived",
Pending: "pending",
} as const;
type Status = (typeof Status)[keyof typeof Status];
const current: Status = Status.Active;This gives you named constants for runtime code and a strict union for type checking.
Keys and values are different unions
You can derive either side of an object:
const HTTP_METHODS = {
Read: "GET",
Create: "POST",
Replace: "PUT",
} as const;
type MethodName = keyof typeof HTTP_METHODS;
// "Read" | "Create" | "Replace"
type Method = (typeof HTTP_METHODS)[keyof typeof HTTP_METHODS];
// "GET" | "POST" | "PUT"Use keyof typeof when you need the property names. Use indexed access with keyof typeof when you need the property values.
| Desired union | Type expression |
|---|---|
| Object keys | `keyof typeof HTTP_METHODS` |
| Object values | `(typeof HTTP_METHODS)[keyof typeof HTTP_METHODS]` |
| Array elements | `(typeof ROLES)[number]` |
A useful mental model
The type expression does not read values while the program runs. It reads the type that TypeScript inferred from the value during compilation.
If you change the array, the union changes automatically:
const ROLES = ["admin", "editor", "viewer", "owner"] as const;
type Role = (typeof ROLES)[number];
// "admin" | "editor" | "viewer" | "owner"The compiler then checks every use of Role against the updated set.
Common mistakes
- Forgetting
as const, which widens an array tostring[]ornumber[]. - Writing
typeof ROLES[number]without parentheses. Use(typeof ROLES)[number]for clarity and correct parsing. - Using
keyof typeof Statuswhen you need values rather than keys. - Treating the derived union as a runtime list. Types disappear after compilation, so use the original array or object for runtime checks.
- Passing a readonly tuple to a function that requires a mutable array. A function that only reads should usually accept
readonlyvalues.
Exercise
Given const LEVELS = ["low", "medium", "high"] as const, write a type named Level containing exactly those three string literals, and write a type named LevelName for an object with keys Low, Medium, and High whose values are the three levels.
Show answer
type Level = (typeof LEVELS)[number]; For the object, use const LevelName = { Low: "low", Medium: "medium", High: "high" } as const; and then type LevelNameValue = (typeof LevelName)[keyof typeof LevelName];.