skip to content
Alvin Lucillo

Const assertion and type operators

/ 2 min read

💻 Tech

The code below shows log function that takes in a status, which is any of the StatusTypes. This ensures that the function only accepts valid values that Typescript linter will inform you about.

Status is created by inferring the literals as types. They are read-only properties. You can use them just like an enum. For example, Status.Ouvert.

Since we’re using Typescript, we can make use of type safety, which is why we have argument status of type StatusType. This is a way to ensure we only receive the values of what Status represents. One of the use case is, in VS Code, if you pass any random string to log function, the code editor’s linter will show that as an error since a string literal isn’t a StatusType. StatusType is a valid type; however, in the example below, a random value was accepted. If you run this in an environment without linters, like in my case, I used JSFiddle, this will work. The point here is we have this system in place to prevent possible misrepresentation of data.

Now, back to the StatusType, I mentioned it’s a valid type. This is because of this declaration: typeof Status[keyof typeof Status]

  • Status[keyof typeof Status] - this is accessing all the keys of Status, creating a union of values: "Ouvert" | "Ferme". typeof Status reflects the structure of the Status constant object. keyof typeof Status extracts all the keys from the Status type to make a union of keys. keyof typeof Status is wrapped in square brackets tells Typescript to look up the type of each property in the Status object.
const Status = {
  Ouvert: "Ouvert",
  Ferme: "Ferme"
} as const;

type StatusTypes = typeof Status[keyof typeof Status];

function log(status: StatusTypes) {
    switch (status) {
        case Status.Ouvert: console.log("Bienvenue"); break;
        case Status.Ferme: console.log("Desolee"); break;
        default: console.log("Quoi?")
    }
}

log(Status.Ouvert); // Bienvenue
log(Status.Ferme); // Desolee
log("Hello"); // Quoi?