So, I've got:
interface Foo {
type: FooType;
}
Which one is better to be used as FooType
here:
Type alias?
type FooType = 'BAR' | 'BAZ';
Or string-based enum?
enum FooType {
BAR = 'BAR',
BAZ = 'BAZ'
}
What are the pros and cons of the two?
Your first example (which you call a "type alias") is actually called a string literal type.
I think it's down to personal preference.
enums
const enum
to avoid this)string literal
string
typed values, you usually have to assert to any
before asserting to your valuelet x: string
let y: FooType
y = x as any as FooType
(edit: hmm, looks like they fixed this)
I used to prefer enums, but lately I've been leaning towards string literal types. Again, I think it all comes down to personal preference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With