One benefit of this approach is being able to check at runtime whether a string is a member of the enum:
functionisSuit(value:string): value isSuits{returnObject.keys(Suits).includes(value)}
The alternative for enum is using a union type:
typeSuit="hearts"|"diamonds"|"spades"|"clubs"
Type information doesn't exist at runtime, how can we check at runtime if a string is a member of the union type?
functionisSuit(value:string): value isSuit{return["hearts","diamonds","spades","clubs"].includes(value asSuit)}
This works but there is an issue with this approach... When you add or remove members, we need to update the array. This is prone to errors because we might forget to update the array or the type. How can we do this automatically?
constALL_SUITS=['hearts','diamonds','spades','clubs']asconst;typeSuitTuple=typeofALL_SUITS;typeSuit=SuitTuple[number];functionisSuit(value:string): value isSuit{returnALL_SUITS.includes(value asSuit)}
We define the possible options using an array with a const assertion. A const assertion tells the compiler to infer the narrowest or most specific type it can for an expression. If you leave it off, the compiler will use its default type inference behavior, which will possibly result in a wider or more general type.