Declare the array as const and index its type with number: const ROLES = ["admin", "editor", "viewer"] as const; then type Role = (typeof ROLES)[number]; gives "admin" | "editor" | "viewer". For an object, keyof typeof obj is the union of its keys and (typeof obj)[keyof typeof obj] the union of its values.
A union type such as "admin" | "editor" | "viewer" exists only while TypeScript checks the code; at runtime it is gone, so you can't loop over it or test a string against it. The fix is to write the list once as a value, an array or an object, and read the type off it. Then the array serves the runtime code, the union serves the checker, and adding a member updates both. The sections below cover the array form, why it needs as const, checking an unknown string against the union, key and value unions from objects (keyof typeof and "valueof"), the reverse direction from a union or an interface to an array, and helper functions that infer the union for their callers. Each example runs on this page: hit Run, then edit the code and run it again.
1as const and (typeof arr)[number]Recommended
Two steps. as const tells TypeScript to keep the exact strings and treat the array as a readonly tuple, so its type is readonly ["admin", "editor", "viewer"] instead of string[]. Then typeof ROLES moves from the value to its type, and indexing that type with [number] asks for the type of an element at any numeric index: the union of all three. The parentheses are optional (typeof ROLES[number] parses the same way) but make the order clear.
// The array is the single source of truth: it exists at runtime... const ROLES = ["admin", "editor", "viewer"] as const; // ...and the union type is read off it: "admin" | "editor" | "viewer" type Role = (typeof ROLES)[number]; function canPublish(role: Role): boolean { return role === "admin" || role === "editor"; } // Loop over the array at runtime, with each item typed as Role for (const role of ROLES) { console.log(`${role.padEnd(6)} can publish: ${canPublish(role)}`); } // One element type per position, too: ROLES[0] has the type "admin" type First = (typeof ROLES)[0]; const first: First = ROLES[0]; console.log(first, ROLES.length); // Adding a role to the array adds it to the union: nothing else to update console.log(JSON.stringify(ROLES));
Output
The loop prints admin can publish: true, editor can publish: true and viewer can publish: false, then admin 3 and the array as JSON. The array and the union can't drift apart, because there is only one list. A value outside it is rejected, for example const r: Role = "guest"; gives error TS2322: Type '"guest"' is not assignable to type '"admin" | "editor" | "viewer"'. The tuple is readonly as well, so ROLES.push("guest") is error TS2339: Property 'push' does not exist on type 'readonly ["admin", "editor", "viewer"]'. That is deliberate: a list that grows at runtime can't back a type fixed at compile time.
2Without as const the union is just string
The most common reason this "doesn't work" is a missing as const. A plain array literal of strings is inferred as string[], because TypeScript assumes you may push other strings into it later. Its element type is then string, and a union derived from it accepts anything. The embed below puts both versions side by side, and it fails on purpose: the typo on the loose type compiles, the same typo on the as const type stops the build, so nothing runs.
// Without as const, the array is widened to string[]... const loose = ["admin", "editor", "viewer"]; type LooseRole = (typeof loose)[number]; // string // ...so any string is a LooseRole, typos included. No error here. const typo: LooseRole = "admn"; // With as const the literals survive, and the same typo is caught const ROLES = ["admin", "editor", "viewer"] as const; type Role = (typeof ROLES)[number]; const role: Role = "admn"; console.log(typo, role);
Output
The only error is on line 12: error TS2820: Type '"admn"' is not assignable to type '"admin" | "editor" | "viewer"'. Did you mean '"admin"'? Line 6 is accepted: run the first half on its own and it prints admn. An annotation undoes as const too: with const ROLES: readonly string[] = [...] as const the declared type wins, the union is string again and the typo compiles. Leave the array unannotated and let as const do the work.
3Check that a string is in the union
Strings from a URL, a form or JSON are typed string, and the obvious check, ROLES.includes(input), doesn't compile: on a readonly tuple, includes only accepts the tuple's own element type, so you get error TS2345: Argument of type 'string' is not assignable to parameter of type '"admin" | "editor" | "viewer"'. Widen the array to readonly string[] for the call and wrap it in a type predicate, value is Role, so a true result narrows the string to the union.
const ROLES = ["admin", "editor", "viewer"] as const; type Role = (typeof ROLES)[number]; // ROLES.includes(value) with a plain string is error TS2345, because // includes() on this tuple only accepts a Role. Widen the array for the // check and let the type predicate narrow the value. function isRole(value: string): value is Role { return (ROLES as readonly string[]).includes(value); } function permissions(role: Role): string { switch (role) { case "admin": return "everything"; case "editor": return "write"; case "viewer": return "read"; } } // Strings from a query string, a form or JSON are only string const inputs: string[] = ["editor", "guest", "ADMIN", "viewer"]; for (const input of inputs) { if (isRole(input)) { // Inside this branch, input has the type Role console.log(`${input}: ${permissions(input)}`); } else { console.log(`${input}: not a role (expected ${ROLES.join(" | ")})`); } }
Output
editor and viewer pass and reach permissions, which only accepts a Role; guest and ADMIN print not a role (expected admin | editor | viewer), since the comparison is exact and case-sensitive. The switch in permissions needs no default: it covers every member of the union, which check a switch is exhaustive explains. For type guards in general, see check a type at runtime.
4Keys and values of an object: keyof typeof and ValueOf
When each member carries data, use an object instead of an array. keyof typeof reads right to left: typeof HTTP_STATUS is the object's type, and keyof turns that type into the union of its keys. TypeScript has no built-in valueof, but indexing a type with all of its keys gives the union of its values, so type ValueOf<T> = T[keyof T] is the one-line version people ask for. The same works on an enum: keyof typeof Color is the union of its member names (see loop through an enum).
// An object instead of an array: each key maps to a value const HTTP_STATUS = { ok: 200, created: 201, notFound: 404, } as const; // typeof turns the value into a type; keyof takes that type's keys type StatusName = keyof typeof HTTP_STATUS; // "ok" | "created" | "notFound" // Indexing with all the keys gives the values: the "valueof" people ask for type ValueOf<T> = T[keyof T]; type StatusCode = ValueOf<typeof HTTP_STATUS>; // 200 | 201 | 404 function codeFor(name: StatusName): StatusCode { return HTTP_STATUS[name]; // a key typed StatusName indexes without a cast } function nameFor(code: StatusCode): StatusName { // Object.keys returns string[], so say what the keys are const names = Object.keys(HTTP_STATUS) as StatusName[]; return names.find((name) => HTTP_STATUS[name] === code)!; } console.log(codeFor("notFound")); console.log(nameFor(201)); // The same works for an interface's property types interface User { id: number; name: string; active: boolean; } const field: ValueOf<User> = true; // number | string | boolean console.log(typeof field);
Output
Prints 404, created and boolean. Without as const the values would widen to number, and StatusCode with them; the keys stay exact either way. Typing the parameter StatusName is also what makes HTTP_STATUS[name] legal. With a plain name: string it compiles here, but with strict on, as in most projects, it is error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ readonly ok: 200; readonly created: 201; readonly notFound: 404; }'. (this page's compiler runs without strict). The as StatusName[] cast on Object.keys is explained in loop through an object.
5The other way: a union or interface keys as an array
Going from an existing union, or an interface, to an array of its members is not possible directly, because the types are erased before the code runs: Object.keys(User) on an interface fails with error TS2693: 'User' only refers to a type, but is being used as a value here. The best fix is to turn the code around and derive the type from an array, as in section 1. When the union comes from somewhere you can't change, write its members out once as the keys of an object and let satisfies Record<Fruit, true> check that the list is complete.
// The union already exists, and you need its members at runtime type Fruit = "apple" | "banana" | "cherry"; // List every member once as a key. satisfies checks the object against // Record<Fruit, true>: a missing or extra key is a compile error. const FRUIT_SET = { apple: true, banana: true, cherry: true, } satisfies Record<Fruit, true>; const FRUITS = Object.keys(FRUIT_SET) as Fruit[]; console.log(FRUITS); // The same trick lists the keys of an interface interface User { id: number; name: string; email: string; } const USER_FIELDS = Object.keys({ id: true, name: true, email: true, } satisfies Record<keyof User, true>) as (keyof User)[]; // For example, copy only the User fields out of a wider object const row = { id: 7, name: "Ada", email: "[email protected]", password: "hunter2" }; const user = {} as Record<keyof User, unknown>; for (const key of USER_FIELDS) { user[key] = row[key]; } console.log(USER_FIELDS.join(", ")); console.log(JSON.stringify(user));
Output
Prints [ 'apple', 'banana', 'cherry' ], then id, name, email and {"id":7,"name":"Ada","email":"[email protected]"}: the password never reaches user. The check is what makes this safe. Drop cherry and the build stops with error TS1360: Type '{ apple: true; banana: true; }' does not satisfy the expected type 'Record<Fruit, true>'.; add durian and it is error TS2353: Object literal may only specify known properties, and 'durian' does not exist in type 'Record<Fruit, true>'. A plain array can't give that guarantee, because nothing stops it from leaving a member out.
6In a helper function: const type parameters
A function that takes a list and should keep its literal types needs the caller to write as const, or, since TypeScript 5.0, a const modifier on its type parameter: function oneOf<const T extends readonly string[]>(options: T) infers readonly ["S", "M", "L"] from a plain array literal, so T[number] is the union. Older answers build the same thing with a tuple(...args) helper; the const modifier replaces it.
// A helper that takes a list and returns a parser for its members. // The const modifier (TypeScript 5.0) infers T as the literal tuple, // as if the caller had written as const. function oneOf<const T extends readonly string[]>(options: T) { return (value: string): T[number] | undefined => options.find((option) => option === value); } const parseSize = oneOf(["S", "M", "L"]); // returns "S" | "M" | "L" | undefined type Size = NonNullable<ReturnType<typeof parseSize>>; const sizes: Size[] = []; for (const text of ["M", "XL", "S"]) { const size = parseSize(text); if (size !== undefined) { sizes.push(size); } } console.log(sizes); // Without const, the same call infers string[] and the union is lost function oneOfLoose<T extends readonly string[]>(options: T) { return options; } const loose = oneOfLoose(["S", "M", "L"]); loose.push("XXXL"); // allowed: loose is string[] console.log(loose);
Output
The parser keeps M and S and drops XL, so sizes prints [ 'M', 'S' ]. Without the modifier, T is inferred as string[], which is why loose.push compiles and the last line prints [ 'S', 'M', 'L', 'XXXL' ]. The readonly in the constraint lets callers pass an as const array as well as a literal. Pulling Size out of the parser's return type uses ReturnType, covered in get the return type of a function.
7Which should you use?
| Method | Type you get | Runtime list | Best for |
|---|---|---|---|
| (typeof arr)[number] + as const | Union of the values | The array itself | A fixed list of strings: the default |
| (typeof arr)[number], no as const | string (union lost) | The array itself | Nothing; add as const |
| keyof typeof obj | Union of the keys | Object.keys (with a cast) | Lookup tables, config objects |
| ValueOf<typeof obj> | Union of the values (as const) | Object.values | The values of a lookup table |
| satisfies Record<U, true> | Uses an existing union | Object.keys (with a cast) | A union or interface you can’t change |
| <const T extends readonly string[]> | Union per call (T[number]) | The argument | Helpers that take a list from the caller |
Frequently asked questions
What does keyof typeof mean in TypeScript?
It is two operators. typeof obj in a type position gives the type of the value obj, and keyof turns a type into the union of its keys. So for const HTTP_STATUS = { ok: 200, created: 201 }, keyof typeof HTTP_STATUS is "ok" | "created". You need both because keyof only works on types and HTTP_STATUS is a value. The same applies to enums: keyof typeof Color is the union of the member names, while keyof Color gives the keys of a string or number (methods like "charAt"), which is rarely what you want.
Is there a valueof similar to keyof in TypeScript?
Not built in, but it is one line: type ValueOf<T> = T[keyof T]. Indexing a type with the union of all its keys gives the union of all its property types. For an object value, write ValueOf<typeof obj> or (typeof obj)[keyof typeof obj], and declare the object as const so the values stay literal (200 | 201 instead of number).
Can I get the keys of an interface as an array of strings?
Not from the interface alone: interfaces are erased at compile time, and Object.keys(User) fails with error TS2693: 'User' only refers to a type, but is being used as a value here. Either list the keys in an object checked with satisfies Record<keyof User, true> and call Object.keys on it, so a missing or extra key is a compile error, or start from const USER_KEYS = ["id", "name"] as const and build the type from (typeof USER_KEYS)[number].
Why is it (typeof ROLES)[number] and not (typeof ROLES)[]?
An indexed access type T[K] gives the type of the property K of T. Arrays and tuples are indexed by numbers, so (typeof ROLES)[number] means "the type of the element at any numeric index", which for a tuple is the union of all its element types. (typeof ROLES)[0] gives just the first one, "admin". T[] is different: it is the syntax for an array of T.
How do I pass an as const array to a function that takes string[]?
Change the parameter to readonly string[]. An as const array is readonly, and passing it to string[] fails with error TS2345: Argument of type 'readonly ["admin", "editor", "viewer"]' is not assignable to parameter of type 'string[]'. because the function could push to it. A function that only reads its argument should declare it readonly string[] anyway; it then accepts both mutable and readonly arrays.
Should I use an enum or an as const array?
For a list of strings, an as const array or object is usually simpler: the union type accepts plain string literals such as "admin", the values are ordinary arrays you can loop over, and nothing extra is generated. An enum makes callers write Role.Admin and emits a runtime object; it suits teams that want named members.
Run it yourself
Open any of these in the full TypeScript editor to tweak, run and share.
TypeScript playground