Typescript Basics: Enums and Generics (Part 3)

Francesca Dreith
3 min readOct 3, 2020

--

Photo by Clément H on Unsplash

This post goes over the basics of enums and generics in Typescript. I covered basics types and functions usage in part 1, and interfaces, literal types, union and, intersection types in part 2.

Enums

Enums, short for enumerations, are a data type used in most object-oriented languages. Enums allow a way for developer to declare a group of named constants, in other words a set of possible values. In Typescript enums can be numeric, a string, or heterogeneous.

Enums are defined with the keyword enum.

Numeric Enums

Numeric enums store string values as numbers. If numbers are not assigned as in the example above, then the values start with 0 and increase by 1. For example, the value of Snacks.popcorn is 0, Snacks.chips is 2, and so forth.

You can also initialize the first value, which will give subsequent Enum members one integer greater than the next. For instance, in the example below, Snacks.chips would have the value of 7.

The values can also be initialized to various numbers, they do not need to be sequential.

Computed Enums are numeric enums that include a computed numeric value. In the following example Snacks.popcorn and Snacks.chips are computed values.

String Enums

String enums are initiated with a string instead of having a numeric value. String enums need to be individually initialized because they cannot be auto-incremented as numeric enums can.

String enums can be accesses through either dot notation (Snacks.popcorn) or bracket notation (Snacks[‘popcorn’]).

Heterogeneous Enums

Heterogeneous enums are when you initialize enums with both strings and numbers.

Generics

Generics are useful when we want to pass in a variety of types to a component.

Using generics are similar to using any, except any doesn’t account for whether the argument type and the return type match. Instead of any, we use type variables.

You can use generics with non-generic types.

When using generics we can only use general methods that are available for every type.

In the example below we can use .length because it is being called on an array of generics.

Generic Interfaces

Generics can be added to interfaces. In the below example I added the type variable of T for timeOfSnack, and the type variable of S for snack. I included a function to demonstrate how we can use our generic interfaces.

--

--