Skip to content
UniCircle
EasyConceptualTypeScript

Enums and type assertions

Question JS-TS-004

What are enums in TypeScript, and what alternatives do many teams prefer? What is a type assertion, and why should you use it sparingly?

Show the explanation

Model answer. An enum gives friendly names to a fixed set of values, and, unlike most TypeScript features, it produces real JavaScript code at runtime:

TypeScript
enum Role { Student = 'STUDENT', Admin = 'ADMIN' }
function canEdit(r: Role) { return r === Role.Admin; }

Many teams prefer a union of string literals, which disappears at compile time and works naturally with plain JSON:

TypeScript
type Role = 'STUDENT' | 'ADMIN';
const ROLES = ['STUDENT', 'ADMIN'] as const;   // a runtime list when needed

A type assertion (value as Type) tells the compiler "trust me, it is this type". It changes nothing at runtime; if you are wrong, the bug appears later as a crash.

TypeScript
const input = document.getElementById('email') as HTMLInputElement;  // reasonable
const user = JSON.parse(text) as User;   // unsafe: nothing checked that the data is a User

Prefer narrowing with checks (type guards) or validating data, and keep assertions for cases you have actually verified.

Original UniCircle question. Last reviewed 22 Oct 2026.