Lesson 7 of 10

Literal types

Goal

A fixed set of values

01

Explanation

A value can itself be a type: the type "md" accepts only the string "md". This is called a literal type. A union of several values, like "sm" | "md" | "lg", describes a fixed set of values and accepts nothing else. It does the job other languages use an enum for, and it's removed when the code is compiled, so it adds no code at all.

The benefit is that a typo becomes a type error. Right now padding("xl") returns 16 without any warning, because the final return 16 catches every value that isn't "sm" or "md". Once you add the type, that call is rejected before the code runs.

Watch out for the widening you saw in the type inference lesson: the type of let preferred = "lg" is string, not "lg", so it isn't accepted where a Size is expected. The fix is to use const, or to write the variable's type explicitly: let preferred: Size = "lg".

02

Your task

Define type Size with the three values and make it the type of the padding parameter. Then fix the two errors the compiler will reveal: preferred, and the line that passes "xl".

Checks

6 checks
  1. No type errors
  2. Size accepts the three values
  3. Size rejects any other value
  4. padding rejects the wrong value
  5. preferred is accepted where a Size is expected
  6. padding returns 4, 8 and 16
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.