Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is in ENUM typescript

Tags:

typescript

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

like image 447
Miomir Dancevic Avatar asked Jun 25 '26 03:06

Miomir Dancevic


1 Answers

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%;
}
like image 97
Behemoth Avatar answered Jun 27 '26 00:06

Behemoth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!