Enums and as const
An enum is a named set of constants. TypeScript has them, but many teams now prefer simple string unions or as const objects, because they produce less extra code.
Fixed sets of values - statuses, payment methods, sizes - appear in every app. TypeScript offers enums, but string unions and as const objects are often simpler and produce no extra JavaScript.
Example
as const
as const tells TypeScript the values will never change, so it keeps the exact values as types:
Example
Example
Tip: the GST rates above are just example numbers for the lesson. Real rates change - always use the current official rates in a real shop.
Key points
- enum creates named constants.
- as const keeps exact values as types.
- keyof typeof gets an object's keys as a union.
📝 Test yourself
1. What does as const do to an array of strings?
2. keyof typeof GST gives...
3. Fill in the keyword to declare an enum:
Size { S, M, L }
