8

I have some emun like this

export enum Languages {
  nl = 1,
  fr = 2,
  en = 3,
  de = 4
}

and some const language ='de'; I only need to check does enum constraint const language, i know with array I can do includes but how to check ENUM?

Also I know i can check like this

if (type in Languages) {
}

but this work is it number and not string

2 Answers 2

8

You can use Object.keys() in order to access the enum keys followed by a simple Array.prototype.includes():

enum Languages {
  nl = 1,
  fr = 2,
  en = 3,
  de = 4,
}

const language = "de";

console.log(Object.keys(Languages).includes(language)); //true

TypeScript playground

This works because an Enum, when transpiled into JavaScript, becomes nothing more than a simple object:

var Languages;
(function(Languages) {
  Languages[(Languages["nl"] = 1)] = "nl";
  Languages[(Languages["fr"] = 2)] = "fr";
  Languages[(Languages["en"] = 3)] = "en";
  Languages[(Languages["de"] = 4)] = "de";
})(Languages || (Languages = {}));

console.log(Languages);
.as-console-wrapper {
  min-height: 100%;
}

Sign up to request clarification or add additional context in comments.

1 Comment

Imagine using two O(n) operations just to check if a variable is an enum member...
0

Let's do it in O(1) ...

Given generic invariant function -

function invariant(condition: unknown, message?: string): asserts condition {
  if (condition) return
  throw Error(`Invariant violation: ${message ?? "truthy value expected"}`)
}

Write invariantLanguage using keyof typeof Language -

function invariantLanguage(lang: string): asserts lang is keyof typeof Language {
  invariant(lang in Language, `"${lang}" is not a valid language`)
}

Now you can use invariantLanguage on your string input -

// ...

enum Language {
  nl = 1,
  fr = 2,
  en = 3,
  de = 4,
}

const x = "en"
invariantLanguage(x)
console.log(x) // : "en"

const y = "foo"
invariantLanguage(y) // ERROR Invariant violation: "foo" is not a valid language
console.log(y) // : never

Verify on typescript playground.


It is also demonstrated working properly with string enums -

// ...

enum Language {
  nl = 1,
  fr = 2,
  en = 3,
  de = 4,
  ja = "japanese", // also works if you have strings
}

const x = "ja"
invariantLanguage(x)
console.log(x) // : "ja"

Notice is does not mistake a value for a key -

const y = "japanese"
invariantLanguage(y) // ERROR Invariant violation: "japanese" is not a valid language
console.log(y) // : never

Verify on typescript playground.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.