Are enums initialized correctly when they are read from a data source?

69 Views Asked by At

In Loopback 4, you can create models which are then connected to a data source to write them out and read them back in.

So let's say I have this enum:

enum Priority {
  LOW = "LOW",
  MEDIUM = "MEDIUM",
  HIGH = "HIGH"
};

Using the Typescript playground this compiles to:

var Priority;
(function (Priority) {
    Priority["LOW"] = "LOW";
    Priority["MEDIUM"] = "MEDIUM";
    Priority["HIGH"] = "HIGH";
})(Priority || (Priority = {}));

So the values are strings, therefore a database (e.g. MySQL) would be able to store this value without problem.

But let's say this is being read from a database. What is going to be the resulting type? Will I get a runtime error?

2

There are 2 best solutions below

0
On

Typescript types are erased at runtime - values of your enum type will simply be strings at runtime. Extracting a string with one of the expected values for your enum from the database, and then treat it as a value of type Priority will behave as you want.

You only need to ensure that no other code accessing the database sets the priority to value different from the three given ones.

0
On

No, you will not get a runtime error because types are erased at runtime.

When reading your priority field from the database you will likely get it as string because it is stored as such. To maintain type safety you can use what's known as a type assertion. That way you explicitly tell the compiler the string from the database is of type Priority.

For example:

enum Priority {
  LOW = "LOW",
  MEDIUM = "MEDIUM",
  HIGH = "HIGH"
};

function readPriority(): string {
  return "LOW";
}

const priority = readPriority() as Priority;

TypeScript Playground