TS 中字符串枚举和字符串文字类型的区别 [英] Difference between string enums and string literal types in TS
问题描述
假设我想确保 { myKey: '' }
中的 myKey
只包含字符串 foo
, bar
、baz
,我可以通过两种方式实现这一点.
Assuming I want to ensure that myKey
in { myKey: '' }
only contains the strings foo
, bar
, baz
, I could achieve this in two ways.
// with a String Literal Type
type MyKeyType = 'foo' | 'bar' | 'baz';
// or with a String Enum
enum MyKeyType {
FOO = 'foo',
BAR = 'bar',
BAZ = 'baz'
}
我想知道一个比另一个的优缺点在哪里,因为在我看来两者都一样(除了我访问值的方式,例如条件检查).
I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check).
我在 TS 文档中发现的唯一区别是 Enum 在运行时是真实的对象,这在某些情况下可能是可取的.
The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases.
推荐答案
要理解的关键是字符串枚举的值是不透明的.
字符串枚举的预期用例是您不希望其他代码知道或关心支持 MyKeyType.FOO
的文字字符串是什么.这意味着您将无法将 文字字符串 "bar"
传递给接受 MyKeyType
的函数——您必须改写 MyKeyType.BAR
.
The intended use case for a string enum is that you don't want other code to know or care what the literal string backing MyKeyType.FOO
is. This means that you won't be able to, say, pass the literal string "bar"
to a function accepting a MyKeyType
-- you'll have to write MyKeyType.BAR
instead.
这篇关于TS 中字符串枚举和字符串文字类型的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!