#Preventing enum values from losing their type

9 messages · Page 1 of 1 (latest)

final matrix
#
half adderBOT
#

@final matrix Here's a shortened URL of your playground link! You can remove the full link from your message.

arcanis_mn#0

Preview:```ts
enum Foo {
Hello,
World,
}

const vals = {
// ^?
// Is there a way to make it {[Foo.Hello]: number; [Foo.World]: number} instead?
[Foo.Hello]: 1,
[Foo.World]: 2,
} satisfies Record<Foo, any>;```

echo thorn
#

Is there something functionally wrong with the result or is it just the intellisense not displaying the way you expect?

final matrix
#

I have other enums and I don't want them to conflict

half adderBOT
#

@final matrix Here's a shortened URL of your playground link! You can remove the full link from your message.

arcanis_mn#0

Preview:```ts
enum Animal {
Cat,
Dog,
}

const animals = {
[Animal.Cat]: 1,
[Animal.Dog]: 2,
} satisfies Record<Animal, any>;

enum Food {
Apple,
}

const myAnimal = animals[Food.Apple];```

echo thorn
#

Yeah, not sure there's a way to prevent that with numeric enums. That's structurally fine, and enums are kinda nominal, but not entirely

#

For a long time numeric enums were basically just number:

enum Animal {
  Cat,
  Dog,
}
// no error
const animal: Animal = 42;

because they were intended (and still are in some ways) to support cases like bitflags. I know they've been improved a bit and the above no longer compiles, but I don't know if they can actually prevent the case you're running into.

#

Personally, my $0.02USD is that animals[Food.Apple] is a fairly unlikely mistake and you probably don't need the type-checker to catch it, but otherwise you may have to roll your own nominal typing.