TypeScript · Middle · Question 16 of 75

Why is an as const object often used instead of an enum?

const Status = { Active: 'active', Banned: 'banned' } as const;
type Status = typeof Status[keyof typeof Status];

Explanation

The object is standard JS: it can be iterated and is compatible with erasable syntax mode (Node.js type stripping). The type is a string union that also accepts literals from an API. Numeric enums, by contrast, accept any number and create a reverse mapping. Enums weren't removed.

Further reading

Problem with a question

TypeScript · Middle · question 16

Test yourself

Take the TypeScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz