bhylu.com

Advertisements

TypeScript Enums

An enum creates named values and usually a runtime object. A string-literal union may be simpler when all you need is a small vocabulary with no runtime enum lookup.

How it works

A collection method has two stable textual values. A string enum keeps its runtime representation readable and avoids relying on implicit numeric positions. Numeric enums can have reverse mappings; string enums do not provide the same reverse lookup. Changing serialized enum values is a data-contract change even if all current TypeScript references still compile.

Run the code

Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.

For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.

Example

lesson.ts

enum CollectionMethod { Desk = "desk", Locker = "locker" }
function describe(method: CollectionMethod): string {
  return method === CollectionMethod.Desk ? "Speak to the desk" : "Use the locker code";
}
console.log(describe(CollectionMethod.Locker));

Expected result

Use the locker code

The argument is one named enum member and the function chooses the corresponding instruction. This lesson uses an ordinary enum that the existing runner can transpile. const enum has different compilation and distribution concerns, especially with isolated transpilers; it is not a universal optimization to apply blindly.