0

I have two enums which are defined like this:

enum Ed {
  up,
  down,
  left,
  right,
}

//or 

enum Es {
  A = "a",
  B = "b",
  C = "c",
}

So I need a function isStringEnum which for isStringEnum(Ed) or isStringEnum(Ed.up) will return false. For isStringEnum(Es) or isStringEnum(Es.A) will return true.

Thanks

3
  • 2
    enums can have numeric and string members simultaneously. What should the function return for this case? Commented Sep 3, 2022 at 0:04
  • Let's assume these are either strictly numeric or strictly string based enums. Commented Sep 3, 2022 at 0:25
  • You could just check whether all the property values are strings or not like this. Does that meet your needs? (Note that a numeric enum will have some string property values, since they include reverse mappings). If so I could write up an answer; if not, please show the use case where it fails. (You will need to mention me via @jcalz if you want me to be alerted, btw) Commented Sep 3, 2022 at 0:29

1 Answer 1

1

This should do the trick:

function isStringEnum(e: object){
  return Object.entries(e).every(e => typeof e[1] === "string")
}

console.log(isStringEnum(Ed)) // false
console.log(isStringEnum(Es)) // true

Playground

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

6 Comments

This works, but involves iteraing through all values of the enum. Is it possible to get the answer in O[1]?
@husayt - You could just check the first element.
@TobiasS. No you can't. The first element will almost certainly be a reverse mapping if it's a numeric enum. Try yourself and see.
@husayt I don't see any part of the question where you care about the time complexity (especially since unless you have enums with millions of entries I can't imagine how such things would even be a concern for you). If you care about that you should put it in the question explicitly.
I guess checking the last element could work then.
|

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.