TypeScript example

How to convert a string to an enum in TypeScript

7 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

For a string enum, find the matching value: Object.values(Color).find((c) => c === input). It returns Color | undefined with no cast, so a string that matches nothing can't slip through. To look up by member name instead, check Object.hasOwn(Color, name) and then read Color[name as keyof typeof Color]. Avoid input as Color: it compiles for any string and checks nothing.

A TypeScript enum is a real object at runtime, but its type only accepts the enum's own members: a plain string from a URL, a form or JSON won't type-check where a Color is expected, even when its text is right. Converting means checking the string against the enum and getting back either a member or a clear "no match". The sections below match by value on string enums, show the error a plain string gives, look members up by name with keyof typeof, deal with numeric enums and their reverse mapping, and wrap it all in a generic helper. Each example runs on this page: hit Run, then edit the code and run it again.

1Match the string against the enum’s valuesRecommended

With a string enum, the string you receive is usually the member's value ("GREEN"), not its name (Green). Object.values(Color) is typed Color[], and comparing each entry with the input is allowed because every member is a string, so find hands back Color | undefined. There is no cast anywhere: the only way to get a Color out is for the input to equal one of the values. After the undefined check the result is narrowed to Color and can be used wherever the enum is expected, here as the key of a Record<Color, string>.

find-value.ts
enum Color {
    Red = "RED",
    Green = "GREEN",
    Blue = "BLUE",
}

// Object.values(Color) is Color[], so find() returns Color | undefined:
// no cast, and a string that matches no value comes back undefined.
function parseColor(input: string): Color | undefined {
    return Object.values(Color).find((c) => c === input);
}

const hex: Record<Color, string> = {
    [Color.Red]: "#e5484d",
    [Color.Green]: "#30a46c",
    [Color.Blue]: "#0090ff",
};

for (const input of ["GREEN", "BLUE", "purple", "Green"]) {
    const color = parseColor(input);
    if (color === undefined) {
        console.log(`${input} -> not a Color value`);
    } else {
        // Narrowed to Color here, so it can index Record<Color, string>
        console.log(`${input} -> ${color} ${hex[color]}`);
    }
}

Output

GREEN -> GREEN #30a46c and BLUE -> BLUE #0090ff match. purple doesn't, and neither does Green: that is the member's name, and the match is on values and case-sensitive. If the strings you receive are names, use the lookup in section 3; for case-insensitive input, the helper in section 5. When you only need a yes or no instead of the member, see check if a value exists in an enum.

2Why a plain string is rejected

The first thing most people try is assigning the string directly. TypeScript refuses, because a string enum type only accepts its own members: Color.Green fits, a string doesn't, even one that holds "GREEN". This embed fails on purpose: the type error stops the run before anything executes, and the checker reports error TS2322: Type 'string' is not assignable to type 'Color'.

not-assignable.ts
enum Color {
    Red = "RED",
    Green = "GREEN",
    Blue = "BLUE",
}

const input: string = "GREEN"; // e.g. read from a query string

// A string enum accepts only its own members, never a plain string
const color: Color = input;
console.log(color);

Output

Even the literal is rejected: const c: Color = "GREEN"; gives error TS2322: Type '"GREEN"' is not assignable to type 'Color'. The tempting fix is input as Color, which compiles, but a cast is a promise to the checker, not a conversion. With input set to "purple", input as Color still compiles, the variable prints purple, and Object.values(Color).includes(color) prints false: a value typed Color that isn't one. Even "purple" as Color on a literal compiles. Use a lookup that can fail instead.

3Look up a member by its name

When the string is a member's name ("Green"), index the enum object with it. The enum object's keys are typed keyof typeof Color, the union "Red" | "Green" | "Blue", so the lookup needs name as keyof typeof Color. With strict on, as in most projects, indexing with a plain string fails with error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Color'. (this page's compiler runs without strict, so there Color[name] quietly gives any). The cast is only safe after a runtime check, and the check should be Object.hasOwn, not in.

by-name.ts
enum Color {
    Red = "RED",
    Green = "GREEN",
    Blue = "BLUE",
}

// Look up by member NAME ("Green"), not by value ("GREEN")
function colorFromName(name: string): Color | undefined {
    // hasOwn skips keys every object inherits, such as "toString"
    if (!Object.hasOwn(Color, name)) {
        return undefined;
    }
    return Color[name as keyof typeof Color];
}

for (const name of ["Green", "Blue", "GREEN", "toString"]) {
    console.log(`${name} -> ${colorFromName(name)}`);
}

// Why not the in operator: it also sees inherited keys
console.log("toString" in Color);

Output

The names Green and Blue give GREEN and BLUE; the value GREEN is not a name and gives undefined, the mirror image of section 1. The last line prints true: "toString" in Color sees the method every object inherits, so an in check would let "toString" through and return a function typed as Color. Object.hasOwn only looks at the enum's own keys.

4Numeric enums: names, digits and the reverse mapping

A numeric enum object holds more than its members: TypeScript also adds a reverse mapping from each number back to its name, so Object.keys lists the numbers too. The input can be a name ("Published") or digits ("2"), and each needs its own check. Digits go through Number and are accepted only when the reverse mapping knows them; names go through the same hasOwn lookup as section 3. The numeric branch runs first, so a digit string never reaches the name lookup, where Status["1"] would return the name "Published" typed as a Status.

numeric.ts
enum Status {
    Draft,     // 0
    Published, // 1
    Archived,  // 2
}

// A numeric enum also maps each number back to its name
console.log(Object.keys(Status));

function parseStatus(input: string): Status | undefined {
    const n = Number(input);
    if (input.trim() !== "" && Number.isInteger(n)) {
        // A number: Status[n] is the member's name, or undefined
        return Status[n] !== undefined ? n : undefined;
    }
    if (!Object.hasOwn(Status, input)) {
        return undefined;
    }
    return Status[input as keyof typeof Status];
}

for (const input of ["Published", "2", "7", "Deleted", "toString"]) {
    const status = parseStatus(input);
    if (status === undefined) {
        console.log(`${input} -> not a Status`);
    } else {
        console.log(`${input} -> ${status} (${Status[status]})`);
    }
}

Output

[ '0', '1', '2', 'Draft', 'Published', 'Archived' ] is the reverse mapping at work, and the same mapping turns a member back into its name: Published -> 1 (Published). The range check on 7 matters because TypeScript lets any number into a numeric enum: a literal out of range is caught (const s: Status = 7; gives error TS2322: Type '7' is not assignable to type 'Status'.), but a number variable is not, and const s: Status = n; with n set to 7 compiles and prints 7 undefined. String enums have no reverse mapping, which is one reason they are the usual choice for values that come in as text.

5A reusable parseEnum helper

With several string enums, write the lookup once. The type parameter E extends Record<string, string> accepts any string enum object, and the return type E[keyof E] | undefined is the union of that enum's members, which is the enum type itself: pass Color and you get back Color | undefined, pass Size and you get Size | undefined. Object.values on a generic object is typed string[], so this is the one place a cast is needed, and it is safe because the values come from the enum itself. An ignoreCase flag covers input typed by people.

parse-enum.ts
enum Color {
    Red = "RED",
    Green = "GREEN",
    Blue = "BLUE",
}

enum Size {
    Small = "s",
    Medium = "m",
    Large = "l",
}

// Works for any string enum; the result type is that enum's member type
function parseEnum<E extends Record<string, string>>(
    enumObj: E,
    input: string,
    ignoreCase = false,
): E[keyof E] | undefined {
    const wanted = ignoreCase ? input.trim().toLowerCase() : input;
    const values = Object.values(enumObj) as E[keyof E][];
    return values.find((v) => (ignoreCase ? v.toLowerCase() : v) === wanted);
}

const color: Color | undefined = parseEnum(Color, " green ", true);
const size: Size | undefined = parseEnum(Size, "m");
console.log(color, size);
console.log(parseEnum(Color, "green"));
console.log(parseEnum(Size, "xl", true));

// With a fallback when the input matches nothing
const fallback: Size = parseEnum(Size, "xxl") ?? Size.Medium;
console.log(fallback);

Output

The first line prints GREEN m: " green " matched once it was trimmed and lower-cased. Without the flag, "green" gives undefined, as does "xl", which no size has. When a missing value should fall back to a default, ?? keeps the type exact: parseEnum(Size, "xxl") ?? Size.Medium is a Size and prints m. The helper is for string enums; for numeric ones, use the checks from section 4.

6Which should you use?

Pick by what the incoming string holds: an enum value, a member name, or digits. Every safe option returns undefined for a string that matches nothing; the cast is the only one that doesn't.

MethodMatchesBad inputBest for
Object.values(E).find(v => v === s)ValuesundefinedString enums: the default
E[s as keyof typeof E]Namesundefined after hasOwnInput that holds member names
Number(s) + E[n] checkDigitsundefinedNumeric enums stored as numbers
parseEnum(E, s, ignoreCase)Values, any caseundefinedMany string enums, user input
s as EAnythingPasses through uncheckedOnly values already checked elsewhere

Frequently asked questions

Why do I get "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Color'"?

You indexed the enum object with a plain string, as in Color[name]. With strict (or noImplicitAny) on, TypeScript reports error TS7053 because typeof Color only has the keys "Red" | "Green" | "Blue", not every string. Check the key at runtime with Object.hasOwn(Color, name) and then index with Color[name as keyof typeof Color]. Without the check, the cast silences the error but lets "toString" and typos through.

Is `input as Color` a valid way to convert a string to an enum?

It compiles, but it converts nothing. as only tells the checker to trust you, and the string is passed through as it is: with input set to "purple", input as Color prints purple and Object.values(Color).includes(color) prints false. Use it only on a value you have already checked; otherwise use a lookup such as Object.values(Color).find((c) => c === input) that returns undefined for bad input.

How do I convert an enum member back to a string?

A string enum member already is its string: const s: string = Color.Green holds GREEN. For a numeric enum, the reverse mapping gives the name: Status[Status.Published] is Published. A string enum has no reverse mapping, so to get the name from a value, search the keys: (Object.keys(Color) as (keyof typeof Color)[]).find((k) => Color[k] === "BLUE") returns Blue.

Can I convert a string to a const enum?

Not at runtime. A const enum is erased during compilation and its members are inlined, so there is no object to search. Object.values(Color) on a const enum fails with error TS2475: 'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query., and Color[name as keyof typeof Color] with error TS2476: A const enum member can only be accessed using a string literal. Use a regular enum, or a union of string literals checked against an array.

Why does Object.keys on a numeric enum return numbers as well as names?

TypeScript compiles a numeric enum into an object with two mappings, name to number and number to name, so Object.keys(Status) returns [ '0', '1', '2', 'Draft', 'Published', 'Archived' ]. That is why a name lookup must not accept digit strings: Status["1"] is the name "Published", not a member. Handle digits with Number(input) first, as in section 4. String enums get no reverse mapping, so their keys are only the names.

Should I use a string union instead of an enum?

Often, yes. A union such as type Color = "RED" | "GREEN" | "BLUE", built from an as const array, accepts plain string literals without a conversion step, needs no runtime object of its own and works with erasableSyntaxOnly and Node's built-in type stripping, which reject enums. Parsing a string into it is the same find over the array. Enums still suit code that wants a named namespace such as Color.Green, or numeric values with names.

Run it yourself

Open any of these in the full TypeScript editor to tweak, run and share.

TypeScript playground