#check if any string is member of enum
23 messages · Page 1 of 1 (latest)
Why not just this:
function X<P extends Foo>(p: P): P {
return p;
}
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
enum Foo {
BAR = 'bar'
}
const foo1: Foo = 'bar'
// ^^^^
// Type '"bar"' is not assignable to type 'Foo'.
const foo2: Foo = Foo.BAR
Enums are made to be opaque, their values are invisible outside of its implementation (enum Foo { ... })
hmmmm
If you don't want opaqueness then yeah, you don't want TS enum.
is there a way to expand the enum into its values
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]
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.
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.
well maybe i'll do that, we'll see