Typescript Enums and Polymorphism with Type Matching

Kevin B. Greene

--

Introduction

The Typescript feature that most affects how I code is enums. Enums? Ho-hum. Where have you been? Typescript enums can be used in conjunction with Typescript’s great type-inference to write some very readable polymorphic code.

Overview of Enums

Let’s explore. In JavaScript we typically approximate enums with code like this:

const MediaTypes = {
YOU_TUBE: 1,
IMAGE: 2,
AUDIO_FILE: 3,
VIDEO_FILE: 4
};
// Or...const MediaTypes = {
YOU_TUBE: 'youtube',
IMAGE: 'img',
AUDIO_FILE: 'audio',
VIDEO_FILE: 'video'
};

Then in the rest of our app we can reference MediaTypes.YOU_TUBE or MediaTypes.IMAGE instead of relying on magic string or number values that are easy to mess up causing bugs and weird behavior that’s not always going to be easy to track down. So, this is a step in the right direction.

Typescript has a proper enum type that depending on how you use it may be compiled into code similar to the JS we just looked at.

enum Animal {
BEAR,
LION,
OTTER,
WORM
}
const enum MoreAnimals {
TIGER,
ZEBRA,
MONKEY,
WOLF
}

--

--

Kevin B. Greene

Experienced Software Engineer, passionate about functional programming and the open web.