如何确保 Typescript 字符串枚举具有相同的键和值

Han*_*les 3 enums typescript

我想创建一个通用类型来检查枚举中的以下内容:

  1. 所有字段都是字符串
  2. 所有的值都等于它们自己的键

因此,在这种情况下,以下枚举将被视为“正确”:

enum correct1 {
  bar = 'bar',
  baz = 'baz',
}

enum correct2 {
  quux = 'quux',
}
Run Code Online (Sandbox Code Playgroud)

但以下不会:

enum wrongFoo {
  bar = 'bar',
  baz = 'WRONG',
}

enum wrongFoo2 {
  bar = 1
}
Run Code Online (Sandbox Code Playgroud)

使这种情况发生的正确语法是什么?

jca*_*alz 6

如果您可以进行手动编译时检查(意味着您必须在enum定义后手动编写一些内容),您可以这样做:

type EnsureCorrectEnum<T extends { [K in Exclude<keyof T, number>]: K }> = true;
Run Code Online (Sandbox Code Playgroud)

然后让编译器评估EnsureCorrectEnum<typeof YourEnumObjectHere>. 如果它编译,太好了。如果不是,则有问题:

type Correct1Okay = EnsureCorrectEnum<typeof correct1>; // okay
type Correct2Okay = EnsureCorrectEnum<typeof correct2>; // okay

type WrongFooBad = EnsureCorrectEnum<typeof wrongFoo>; // error!
//   ??????????????????????????????> ~~~~~~~~~~~~~~~
// Types of property 'baz' are incompatible.

type WrongFoo2Bad = EnsureCorrectEnum<typeof wrongFoo2>; // error!
//   ???????????????????????????????> ~~~~~~~~~~~~~~~~
// Types of property 'bar' are incompatible.
Run Code Online (Sandbox Code Playgroud)

错误也相当具有描述性。

好的,希望有帮助;祝你好运!

代码链接