lecture 8 of 110 completed

Fixed lists: enums, const objects and as const

Keep one list as the source of both the values and the type. An enum does that too, but it is code and not only a type, and some tools refuse it.

What you'll learn

  • How as const and typeof turn one list into a type
  • How to read an enum in existing code
  • Why an enum cannot be removed like a type, and what follows from that

A Shelf suite runs the same permission test for every role. The roles exist in two places: a type, and a list to loop over.

type Role = "member" | "librarian" | "admin";

const ROLES: Role[] = ["member", "librarian"];

for (const role of ROLES) {
  console.log("checking " + role);
}
checking member
checking librarian

The compiler reports nothing. The list is a valid list of roles. It is not a list of every role, and the admin test never runs. Somebody added "admin" to the type and forgot the list.

Two copies of one fact drift apart. The fix is one copy.

From a list to a type

Start from the list, because the loop needs real values at run time. Then make the type from it.

const ROLES = ["member", "librarian", "admin"] as const;
type Role = (typeof ROLES)[number];

const role: Role = "admin";

for (const each of ROLES) {
  console.log("checking " + each);
}
checking member
checking librarian
checking admin

Two new pieces do the work.

as const tells the compiler to keep the list exactly as written. Without it, the type of ROLES is string[]. With it, the type is a fixed list of three exact strings, and the list cannot be changed.

typeof ROLES takes the type of that value. Here typeof is used in a type, which is different from the typeof you use in an if. Adding [number] asks for the type of any one item. The result is "member" | "librarian" | "admin".

Add a role to the list and the type has it. There is no second place to forget.

const ROLES = ["member", "librarian", "admin"] as const;
type Role = (typeof ROLES)[number];

const role: Role = "owner";
roles.ts(4,7): error TS2322: Type '"owner"' is not assignable to type '"member" | "librarian" | "admin"'.

A const object

The same works for an object of named values.

const FEES = { daily: 0.5, maximum: 10 } as const;
type FeeName = keyof typeof FEES;

function fee(name: FeeName): number {
  return FEES[name];
}

console.log(fee("daily"));
0.5

keyof gives the names of the fields as a union: "daily" | "maximum". A test can pass only a name that exists.

Reading an enum

Older TypeScript code solves this with an enum. You will meet it, so you need to read it.

enum Role {
  Member = "member",
  Librarian = "librarian",
  Admin = "admin",
}

function canLend(role: Role): boolean {
  return role !== Role.Member;
}

console.log(canLend(Role.Admin));
console.log(Object.values(Role));
true
["member","librarian","admin"]

Role is used as a type in the parameter and as a value in Role.Admin. The last line shows something important. Role exists when the code runs. It is an object, and you can list its values.

An enum is not only a type

The first lecture of the Junior track gave you a rule: types are removed, and what is left is the JavaScript you wrote. An enum breaks that rule. There is no JavaScript enum, so the compiler has to write new code for it. The enum is not removed. It is translated.

That has a practical cost. Some tools run TypeScript by only removing the types, with no translation. Node is one of them. Its documentation says it replaces TypeScript syntax with whitespace, and it lists enum declarations among the features it does not support. TypeScript has a setting for projects that want to stay compatible with such tools, and it reports an enum as an error.

enum Role {
  Member = "member",
  Admin = "admin",
}
roles.ts(1,6): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.

The short constructor form from lecture 5 is in the same group, for the same reason. It makes the compiler write a line of code.

export class LoansPage {
  constructor(private readonly name: string) {}
}
loans-page.ts(2,15): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.

A list with as const has no such problem. Remove as const and the type line, and plain JavaScript is left.

So here is a recommendation, with its reason. Read enums wherever you find them, and keep using them in a project that already does. For new code, write a list or an object with as const. It gives you the same checks and the same values to loop over, and every tool that removes types can run it.

Remember this

Keep a fixed set of values in one list with as const, and make the type from it with typeof. An enum also gives you a type and values, but the compiler must translate it into code. Tools that only remove types refuse it. Read enums, and write as const lists in new code.

Reference: Objects vs Enums in the TypeScript Handbook.

now prove it

Reading is the setup. Solve this exercise in the editor. We check your code with the TypeScript compiler and list each type error.