Uniquely Keyed Values With Typescript Indexable Types | Task

Ole Ersoy
Mar - 30  -  1 min

Scenario

We want an Enum like data structure containing error codes.

We want to be able to use Object.keys() to get the keys and Object.values to get the values.

This is an example:

const errorTypes: ErrorTypes =
{
    DATA_ERROR: 'Data Error',
    NETWORK_ERROR: 'Network Error'
}

Approach

In order to define ErrorTypes we we will use a Typescript Indexable Type.

export interface ErrorTypes {
  [key: string]: string;
}

Now we can get the keys and values like this:

const keys = Object.keys(errorTypes);
console.log(`The keys are ${keys}`);

const values = Object.values(errorTypes);
console.log(`The values are ${values}`);