#Copy const enum to object for indexing

14 messages · Page 1 of 1 (latest)

rustic turtle
#

This is not about indexing a const enum when the option preserveConstEnums is true. I read the issue that it is impossible.
What I did is to use the copy of the enum.

const enum Kind {
  A, B, C
};

const KindName: {[key in Kind]: string} = {
  [Kind.A]: "A",
  [Kind.B]: "B",
  [Kind.C]: "C",
};

console.log(KindName[Kind.A]);

But I can just assign the KindName property to any string. How to force the string value to be the same as corresponding enum property?
Thanks.

dull wigeon
#

How about using regular enums? @rustic turtle

#

They are opaque, so you won't be able to pass a string when the enums is expected
And you won't need to hold references to it's members by copying the object

rustic turtle
#

How about the reverse? Make a const enum from an object. Is it possible?

zenith minnow
#

@rustic turtle you can use a mapped type:

topaz swiftBOT
#
mkantor#0

Preview:ts ... const KindName: {[K in Kind]: typeof Kind[K]} = ...

rustic turtle
#

Sorry, but in the playground I still can do

[Kind.A]: "should be A"
zenith minnow
#

huh, i don't know why i thought that worked. i saw what i thought was the desired type error when i first wrote it, but i must've had another mistake

#

this actually works, but it's hideous:

topaz swiftBOT
#
mkantor#0

Preview:```ts
...
type KindNamesByValue = UnionToIntersection<
{
[K in keyof typeof Kind & string]: Record<
typeof Kind[K],
K
>
}[keyof typeof Kind]

...```

zenith minnow
topaz swiftBOT
#
mkantor#0

Preview:ts ... type KindNamesByValue = { [K in keyof typeof Kind & string as typeof Kind[K]]: K } ...

rustic turtle
#

Perfection. Thanks so much. I always struggle with these keyof typeof thing.