Sub topic 5
Deriving union types from values
What you will build
Many programs keep a list of allowed values, such as user roles, order statuses, or HTTP methods. The same list usually shows up twice: once as a runtime array that you loop over, and once as a union type that the compiler checks. This chapter shows how to write the list once and derive the union from it.
This chapter assumes you know:
- The basic TypeScript types (
string,number, arrays, object types). - The difference between
letandconst. - Union types and literal types such as
"a" | "b". - How
typeofandkeyofwork in type positions. - What
as constdoes to a literal. The earlier chapters cover this, and this chapter uses it without re-teaching it.
The problem: two lists that drift apart
Without as const, you would write the values twice:
type Role = "admin" | "editor" | "viewer";
const ROLES: Role[] = ["admin", "editor", "viewer"];The compiler checks that every element of ROLES is a valid Role. It does not check the other direction. If someone adds "owner" to the union and forgets the array, the code compiles, and a dropdown built from ROLES silently omits the new role. Two copies of one fact will eventually disagree.
The fix is to make the runtime value the single source of truth and compute the type from it. TypeScript can do this because a type can be extracted from a value with typeof. The extraction only gives useful results if the value keeps its literal types, and that is what as const provides.
Deriving a union from a const array
Here is the pattern:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
// "admin" | "editor" | "viewer"The derivation takes two steps.
typeof ROLESreads the type of the value. Because ofas const, that type isreadonly ["admin", "editor", "viewer"], a readonly tuple with a literal type at each position.[number]is an indexed access type. It asks, "what type do you get when you index this with any number?" A tuple has a known type at index 0, 1, and 2. Indexing with the general typenumbermeans "any of those positions", so TypeScript returns the union of all the element types.
Without as const, the first step would produce string[]. Indexing that with number gives string, and you would be back to an unchecked string.
The parentheses around typeof ROLES are not required by the parser, but they make the order of operations clear. Most codebases write them.
Using the derived type
Once Role exists, you can use it anywhere a hand-written union would work:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
const labels: Record<Role, string> = {
admin: "Administrator",
editor: "Editor",
viewer: "Viewer",
};
for (const role of ROLES) {
console.log(role, labels[role]);
}Two things are worth noticing here.
- The loop variable
rolehas typeRole, notstring. That is whylabels[role]compiles. Indexing aRecord<Role, string>with a plainstringwould be an error. Record<Role, string>requires one property for every member of the union. If you add"owner"toROLESand forget to add a label, thelabelsdeclaration fails with a missing-property error. The compiler now tells you about every place that needs updating.
Checking untrusted input with a type guard
Data from a form, a URL, or a JSON response is typed string at best. To turn it into a Role, you need a runtime check. The array you already have is the natural place to look:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value);
}
function parseRole(input: string): Role {
if (!isRole(input)) {
throw new Error(`Unknown role: ${input}`);
}
return input;
}
console.log(parseRole("editor")); // editorThe cast ROLES as readonly string[] is needed because of how includes is typed. On a readonly ["admin", "editor", "viewer"], the method accepts only the element union, so ROLES.includes(value) with a plain string argument is a compile error. Widening the array to readonly string[] lets the call through. The cast is safe here because it only widens the type. It does not claim anything false.
The return type value is Role is a type predicate. When isRole returns true, TypeScript narrows input to Role in the calling code. This is the one place where you tell the compiler something it cannot verify on its own, so the body must be correct. Deriving the type and the check from the same array keeps them in sync.
Deriving a union from an object
Objects work too. A const object gives you named constants, and a union of its values gives you the matching type:
const Status = {
Active: "active",
Archived: "archived",
} as const;
type Status = (typeof Status)[keyof typeof Status];
// "active" | "archived"
const s: Status = Status.Active;Read the type from the inside out.
typeof Statusis{ readonly Active: "active"; readonly Archived: "archived" }.keyof typeof Statusis the union of its property names:"Active" | "Archived".- Indexing the object type with that key union gives the union of the property types:
"active" | "archived".
The value Status and the type Status share one name. This is legal because TypeScript keeps values and types in separate namespaces. In Status.Active the name refers to the value. In const s: Status it refers to the type. Importing Status from a module brings both along.
Keys versus values
The same object can produce two different unions, and it is easy to mix them up:
const Status = {
Active: "active",
Archived: "archived",
} as const;
type StatusKey = keyof typeof Status;
// "Active" | "Archived"
type StatusValue = (typeof Status)[StatusKey];
// "active" | "archived"Use the keys when you want to refer to the names in code, for example in a Record<StatusKey, ...>. Use the values when you want the type of data that is stored or sent over the network. In most programs the stored value is what you want to type, which is why the Status example above takes the values.
The object form also works with numbers:
const Level = {
Low: 1,
Medium: 2,
High: 3,
} as const;
type Level = (typeof Level)[keyof typeof Level];
// 1 | 2 | 3Deriving from an array of objects
Real configuration is rarely a flat list of strings. You can index into an array of objects and then into a property to extract one field across all entries:
const PLANS = [
{ id: "free", seats: 1 },
{ id: "team", seats: 10 },
{ id: "enterprise", seats: 500 },
] as const;
type Plan = (typeof PLANS)[number];
// the union of the three object types
type PlanId = (typeof PLANS)[number]["id"];
// "free" | "team" | "enterprise"
function seatsFor(id: PlanId): number {
const plan = PLANS.find((p) => p.id === id);
return plan ? plan.seats : 0;
}
console.log(seatsFor("team")); // 10(typeof PLANS)[number] is a union of three object types, each with its own literal id and seats. Adding ["id"] selects that property from every member and unions the results. The same technique extracts any field, such as ["seats"], which gives 1 | 10 | 500.
Because the union members are distinct object types that differ in a literal property, Plan behaves like a discriminated union. You can narrow it by checking plan.id.
The whole pipeline
The diagram shows how a single declaration feeds both the runtime and the type system.
Everything on the type side disappears when the code is compiled to JavaScript. Only the array survives. That is why the type guard in isRole matters: it is the only place where a runtime check connects back to the compile-time type.
Common mistakes
Forgetting `as const`
Without it, the derivation compiles but gives you the wide type:
const ROLES = ["admin", "editor", "viewer"];
type Role = (typeof ROLES)[number];
// stringThere is no error. Role is now just string, and every check that depends on it accepts any string. If a derived union looks too wide, check for a missing as const first.
Using `keyof` on the value instead of its type
keyof works on types. Writing it against a value name gives an error:
const Status = { Active: "active", Archived: "archived" } as const;
// type Keys = keyof Status;
// error: 'Status' refers to a value, but is being used as a type here.
// Did you mean 'typeof Status'?
type Keys = keyof typeof Status; // "Active" | "Archived"The error appears only when no type named Status exists. In the earlier example, where a type and a value share the name, keyof Status would silently refer to the type (the string union), which is a different and surprising result. Keep this in mind when you reuse a name.
Applying `keyof typeof` to an array
keyof on an array type returns more than the indices. It includes number, plus names such as "length", "push", and "map". If you want the elements, use [number]. If you want the indices of a tuple, you need a more advanced mapped-type approach that this chapter does not cover.
Building the array at runtime
The literal types come from the source text of the array literal. If the array is computed, the types are lost:
const base = ["admin", "editor"] as const;
const extended = [...base, "viewer"] as const;
// readonly ["admin", "editor", "viewer"] (spreading a const tuple is fine)
const names = ["admin", "editor"].map((s) => s.toUpperCase());
// string[] (the result of a function call is not a literal)Spreading other const tuples into a new as const array works, because the compiler knows each element type. Anything that passes through a function call, such as map, filter, or Object.keys, returns plain string or number types again. If you need a derived list, write it as a literal, or accept that its type is wide.
Trusting the type at a boundary
A derived union describes what the code is supposed to hold. It does not enforce anything at runtime. A value parsed from JSON can claim to be a Role through a cast, and the compiler will accept it. Validate with a guard like isRole wherever data enters your program, and use the derived type only after that point.
Choosing between array and object sources
Both forms produce a union. The choice depends on what else you need.
| Source | Derivation | Best when |
|---|---|---|
| Const array of strings | `(typeof ROLES)[number]` | You need the list itself, for example to render options or validate input |
| Const object | `(typeof Status)[keyof typeof Status]` | You want named constants such as `Status.Active` in code, with values that differ from the names |
| Const array of objects | `(typeof PLANS)[number]["id"]` | Each entry carries extra data, and you want a union of one field |
If the names and the values would be identical, the array is shorter and gives you a list for free. If you want to write Status.Active and not a bare string, use the object. A later chapter compares the object form with TypeScript enums in more detail.
Summary of the pattern
- Declare the values once, as a literal with
as const. - Extract the type with
typeof, then use[number]for arrays or[keyof typeof X]for objects. - Use the type in parameters,
Recordkeys, and variables. - Use the value for loops and runtime checks, and write one type guard to connect the two.
Exercise
Given const SIZES = ["small", "medium", "large"] as const;, write the type Size derived from it. Then say what type Size would be if as const were removed, and why.
Show answer
type Size = (typeof SIZES)[number]; gives "small" | "medium" | "large". Without as const, SIZES is typed string[], so (typeof SIZES)[number] is string. The compiler widens each element of a mutable array literal to string, and indexing an array with number returns its element type.
Exercise
Given const Mode = { Light: "light", Dark: "dark" } as const;, write one type ModeKey for the property names and one type ModeValue for the stored values. Which one would you use as the type of a theme field saved to a database?
Show answer
type ModeKey = keyof typeof Mode; gives "Light" | "Dark". type ModeValue = (typeof Mode)[keyof typeof Mode]; gives "light" | "dark". The saved theme field holds the values, so it should be typed ModeValue.
Exercise
The function function isRole(value: string): value is Role { return ROLES.includes(value); } fails to compile when ROLES is readonly ["admin", "editor", "viewer"]. Explain the error and give the fix.
Show answer
On a readonly tuple of literals, includes accepts only the element union ("admin" | "editor" | "viewer"), and value is a plain string, so the argument is not assignable. Widen the array for the call: (ROLES as readonly string[]).includes(value). The cast only widens the type, so it is safe.