【发布时间】:2019-11-25 16:29:03
【问题描述】:
我正在尝试在打字稿中使用枚举,但它们的类型检查似乎并不十分一致。为什么我可以在没有警告的情况下检查TestEnum.Foo === 'foo',但尝试将'foo' 传递给接受TestEnum 的函数会导致错误。
describe('Test enum functionality', () => {
enum TestEnum {
Foo = 'foo',
Bar = 'bar'
}
// I expected this to work as TestEnum.Foo === 'foo'
test('Can pass string to enum', () => {
const func = (x: TestEnum) => {}
// Error: Argument of type '"foo"' is not assignable to parameter of type 'TestEnum'
func('foo');
});
// Surprised that this worked after I couldn't pass in a string literal to a function
test('compiler can verify that this string literal is an Enum option', () => {
if (TestEnum.Foo === 'foo') {
}
});
// I expect an error here because the compiler should be able to see there is no overlap
test('compiler can verify that this string literal is not an Enum option', () => {
// Error: This condition will always return 'false' since the types 'TestEnum.Foo' and '"asdf"' have no overlap
if (TestEnum.Foo === 'asdf') {
}
});
});
更新
我删除了一些单元测试以更清楚地说明我为什么感到困惑
【问题讨论】:
标签: typescript enums