Enums and const assertions in TypeScript
Fixed sets of values, as enums or literal unions.
enum Status {
Pending = "pending",
Active = "active",
Closed = "closed",
}
const ORDER = ["low", "medium", "high"] as const;
type Priority = (typeof ORDER)[number];
function label(status: Status, priority: Priority): string {
return `${status}/${priority}`;
}
const current = label(Status.Active, "high");
const all = Object.values(Status);
How it works
- A string
enumnames each member's value. as constfreezes an array of literals.(typeof ORDER)[number]derives a union from it.
Keywords and builtins used here
ObjectPriorityStatusasconstenumfunctionnumberreturnstringtype
The run, in numbers
- Lines
- 15
- Characters to type
- 343
- Tokens
- 88
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 62 seconds.
Step 3 of 4 in Primitives & literals, step 3 of 23 in Types & annotations.