打字稿扩展枚举



情况是你有一个常量列表或枚举如何做到这一点?

下面是伪示例代码:

enum MyList
{
A,
B
}
enum MyList2
{
C
}

function test<T>(input:MyList | T):void
{
}
test<MyList2>(123) // compiler does not identify that 123 is not a supported

这是数字枚举的长期问题。 无论出于何种原因(某些向后兼容性它们无法破坏),number被视为可分配给数字枚举,因此您可以毫无错误地执行此操作:

enum E {
V = 100
}
const num = 100;
const e: E = num; // no error 🤔

更重要的是,数字枚举还旨在充当位字段,因此它们有意不要求数字枚举类型的值是特定的声明值之一:

enum Color {
RED = 1,
GREEN = 2,
BLUE = 4
}
const red: Color = Color.RED; // 1
const yellow: Color = Color.RED | Color.GREEN; // 3 🤔
const white: Color = Color.RED | Color.GREEN | Color.BLUE; // 7 🤔
const octarine: Color = Math.pow(Color.BLUE - Color.RED, Color.GREEN); // 9 🤪

是的,我不知道为什么你可以用数字枚举做任何你想要的数学,但你可以。 结果是,基本上任何number都可以分配给任何数字枚举,反之亦然。


如果你想防止这种情况,你可能想放弃实际的枚举,而是使用你控制的行为创建自己的类型和值。 它更冗长,但它可能满足您的需求:

const MyList = {
A: 0,
B: 1
} as const;
type MyList = typeof MyList[keyof typeof MyList]
const MyList2 = {
C: 0
} as const;
type MyList2 = typeof MyList2[keyof typeof MyList2]

它们的行为类似于你的旧枚举(尽管有一些缺失的类型),但它们的行为会更加严格:

function test<T>(input: MyList | T): void {}
test(0); // okay
test(1); // okay
test(2); // okay, 2 is inferred as T
test<MyList2>(123); // error! 123 is not assignable to 0 | 1

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

链接到代码

最新更新