DAY 20 OF 30
Enums
Yesterday, in one sentence
Telling TypeScript to treat a value as a particular type, written with as. It
changes the type without checking or converting anything. You use one when
TypeScript's type for a value does not match what you know the value to be.
Did you say:
- ✓tells TypeScript to treat a value as a particular type
- ✓written with `as`
- ✓checks nothing and converts nothing
- ✓used when TypeScript's type does not match what you know the value to be
Interview question
as const and as?as tells TypeScript to treat a value as a type you name. as const names no
type, it tells TypeScript to infer the narrowest type it can and make everything
readonly.
Did you say:
- ✓`as` names the type
- ✓`as const` changes how the value is inferred
- ✓`as const` also makes it readonly
A literal unionLiteral Union restricts a value to a fixed set of options.
type Alignment = "hero" | "villain";
let side: Alignment = "hero";
An enum does the same job, but it also gives each option a name you refer to it
by, instead of writing the raw value. You write it with the enum keyword, and the
entries inside it are called members.
enum Alignment {
Hero = "hero",
Villain = "villain",
}
Alignment.Hero; // "hero"
The enum's name gives you two things. Alignment is an object holding those values,
and it is also a type. Used as a type it accepts only its own members, and does not
recognise the values attached to them.
let side: Alignment; // can be Alignment.Hero or Alignment.Villain
side = Alignment.Hero; // ok
side = Alignment.Villain; // ok
side = "villain"; // ❌ not assignable to type 'Alignment'
Everywhere else TypeScript uses structural typingStructural Typing: if it looks like a duck, it is a duck. Enums are the exception, and require the exact member rather than a matching value.
Because an enum is a value as well as a type, that object has to exist when the code runs. It is the one piece of TypeScript that is converted into JavaScript at build timeBuild Time rather than stripped out.
If you leave the values off, TypeScript numbers the members from zero instead.
enum Rank {
Alpha, // 0
Beta, // 1
}
Check yourself
An enum compiles to a real object. The others are types and are stripped out at build time.
A type but also a set of named values, written with the enum keyword. It
compiles to an object in JavaScript, and as a type it accepts only its own
members.
Did you say:
- ✓a type but also a set of named values
- ✓written with the `enum` keyword
- ✓compiles to an object in JavaScript
- ✓as a type it accepts only its own members