Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: type alias vs string-based enum

Tags:

typescript

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?

like image 864
Glenn Mohammad Avatar asked Oct 28 '19 17:10

Glenn Mohammad


1 Answers

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

  • Pro you don't need to know what the internal value is
  • Pro (subjective) the code reads well
  • Con they have runtime artifacts (although you can use const enum to avoid this)
  • Con they cannot be ambient

string literal

  • Pro no runtime artifacts (and it can be ambient)
  • Pro no need to pass around the value
    • Con when dealing with string typed values, you usually have to assert to any before asserting to your value
let 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.

like image 180
Tyler Sebastian Avatar answered Nov 19 '22 00:11

Tyler Sebastian