Enums and the alternative in TypeScript
What an enum gives you, and why a const object often beats it.
enum Level {
Debug,
Info,
Warn,
}
const enum Inlined {
Yes = "yes",
}
const LEVELS = {
debug: "debug",
info: "info",
warn: "warn",
} as const;
type LevelName = (typeof LEVELS)[keyof typeof LEVELS];
function log(level: LevelName, message: string): string {
return `[${level}] ${message}`;
}
console.log(Level.Info, Level[1], Inlined.Yes);
console.log(log("warn", "slow"), Object.values(LEVELS));
How it works
- A numeric enum is bidirectional and emits real code.
- A string enum is nominal: two identical strings are not assignable.
- A const object with
as constis erasable and structurally typed.
Keywords and builtins used here
LevelNameObjectasconstenumfunctionreturnstringtype
The run, in numbers
- Lines
- 24
- Characters to type
- 399
- Tokens
- 116
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 82 seconds.
Step 4 of 4 in Primitives & literals, step 4 of 23 in Types & annotations.