sindresorhus / is

Type check values
MIT License
1.68k stars 109 forks source link

Proposal: Add support for enum validation #148

Closed olivierbeaulieu closed 2 years ago

olivierbeaulieu commented 2 years ago

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.

sindresorhus commented 2 years ago

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.

olivierbeaulieu commented 2 years ago

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).
sindresorhus commented 2 years ago

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.