Using TypeScript, comparably to other programming languages, we can define finite numerical (and string-based) sets by using a data structure called enumeration. As I am going to prove later in this article, enumerations fit well together with other TypeScript constructs like namespaces and literals.

Enumeration with numbers

We can create an enumeration type indexed with a number value:

const enum ENumbers {
ONE = 1,
TWO = 2,
THREE = 3,
// ...
}
type TNumbers = 1 | 2 | 3; // etc.

Enumeration with strings

Similarly to numbers, we can define enumeration types using strings, like in the following snippet:

const enum ELetters {
a = 'a',
b = 'b',
c = 'c',
// ...
}
type TLetters = 'a' | 'b' | 'c';

Interoperability of enumerations and namespaces

We can use the name of the enumeration type to define an namespace. We can use such a namespace to e.g. allow a function to belong to a certain type:

enum ECountry {
US = 'US',
UK = 'UK',
DE = 'DE',
FR = 'FR',
}
namespace ECountry {
export const getPrice = (country: ECountry): number => {
switch(country) {
case ECountry.US:
case ECountry.UK:
return 10;
default:
return 5;
}
}
}

Interoperability of enumerations and literals

As our enumeration types might hold a lot of additional code which is not related to the very enumeration aspect of them, we might want to abstract them away (or when we want to distribute a codebase as a library and we don’t want to expose enumeration types). This is possible by defining a type literal which values correspond to the values of the enumeration.

type TCountry = 'US' | 'UK' | 'DE' | 'FR';interface IPricing {
getPrice: (country: TCountry) => number;
}
const getPricing = (): IPricing => ({
getPrice: ECountry.getPrice,
});

Summary

As we might have seen, TypeScript allows us to convey enumeration using either enumeration types or literal types and it is possible to use both approached interchangeably. Personably, I prefer using literal types as the structure is way shorter and I get the same type support from the TypeScript compiler as compared to using enumeration types.

Full-stack Software Developer that loves building products.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store