sindresorhus / is

Type check values

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Proposal: Add support for enum validation

olivierbeaulieu opened this issue · comments

Hello!

I've been wondering whether is could help me validate that a string is a member of a specific enum - I haven't found anything in the library that does that, so I wanted to ask whether that would be a good addition.

Here's what I'm hoping to achieve:

enum MyEnum {
  SOME_VALUE = 'SOME_VALUE'
}

function myFn(param: string) {
  param; // Type is string
  assert.enum(param, MyEnum);
  param; // Type is MyEnum
}

This obviously would not work for const enums - but could be very handy for the rest. Happy to contribute if the proposition makes sense.

The example makes no sense to me. Why would you ever accept string if what you actually want is to accept an enum value? Do you maybe have a more realistic example?

In general, I'm lukewarm to adding support for anything regarding TypeScript enums, as they suck. I love enums in other languages, but the TS one is just bad. More on that.

I see what you mean - maybe I need to clarify a couple things.

  1. We exclusively use non-numeric enums - essentially only strings. Because of the reasons detailed in your first link. But I understand that in designing this library you have to account for the other dangerous cases.
  2. The example I gave might be too simplified - what I'm really trying to achieve here is to have an express api handler validate input from params (type will be string), check if the received string is indeed part of the enum of valid values, and cast it as such if the value is valid (and throw if it isn't).

Alright. I'm going to accept this.

The check should be Object.values(Enum).includes(case).

I also think is.enumCase may be a better name as you're checking the case, not the whole enum itself.