#check if any string is member of enum

23 messages · Page 1 of 1 (latest)

marsh bear
#
enum Foo {
  BAR = 'bar'
}

function X<P extends string>(p: P): P extends Foo ? P : never {
  throw new Error();
}

X("bar") // never

i would've expected this to return P but it returns never. is there a way to do this? am i using the wrong syntax or something?

dense mica
#

Why not just this:

function X<P extends Foo>(p: P): P {
  return p;
}
marsh bear
#

in practice the code looks like

#
  get<P extends string>(type: P): P extends FooTypes ? Foo : Foo | null {
    return FOOS_BY_TYPE[type] ?? null;
  },
#

but its being too strict. i want it to support strings that don't originate directly from typing out FooTypes.BAR, for example a string literal

strange stump
#
enum Foo {
  BAR = 'bar'
}

const foo1: Foo = 'bar'
const foo2: Foo = Foo.BAR
#

!ts

rustic flaxBOT
#
enum Foo {
  BAR = 'bar'
}

const foo1: Foo = 'bar'
//    ^^^^
// Type '"bar"' is not assignable to type 'Foo'.
const foo2: Foo = Foo.BAR
strange stump
#

Enums are made to be opaque, their values are invisible outside of its implementation (enum Foo { ... })

marsh bear
#

hmmmm

strange stump
#

If you don't want opaqueness then yeah, you don't want TS enum.

marsh bear
#

is there a way to expand the enum into its values

strange stump
#

You can use object/array version of enum rather than TS enum.

#

Array version:

const Color = ['red', 'green', 'blue'] as const
type Color = typeof Color[number]

Object version:

const Color = {
    Red: 'red',
    Green: 'green',
    Blue: 'blue',
} as const
type Color = typeof Color[keyof typeof Color]
marsh bear
#

maybe i'll sprinkle that in

strange stump
#

There are some caveats

#

With number enum/const enum.

#

But yeah TS enum is wrong tool for the job here, you clearly don't want opaqueness and are fighting against the language to get around it.

marsh bear
#

indeed

#

the enum already exists though

strange stump
#

The object version is just find and replace to change the = into :, and it's a drop in replacement, don't need to change the code anywhere else.

marsh bear
#

well maybe i'll do that, we'll see