Literal Types
A free lesson from Swipe Coding · TypeScript, level 2 · updated October 2026
By the Swipe team, founded by Colin · how we make lessons
So far, types like string and number describe a whole category of values. TypeScript can also describe a single, exact value as its own type — called a literal type. "left" isn't just a string; it can be the type "left", matching nothing else.
let direction: "left" = "left"; direction = "left"; // fine — matches the literal type exactly direction = "right"; // Error: Type '"right"' is not assignable to type '"left"'.
A single literal type on its own isn't very useful — you'd rarely want a variable that can only ever be one specific value. Literal types show their real strength combined with union types, using | to list every value that should be allowed.
type Direction = "left" | "right"; let move: Direction = "left"; // fine move = "right"; // fine move = "up"; // Error: Type '"up"' is not assignable to type 'Direction'.
This pattern is everywhere in real APIs, because it documents and enforces the exact set of valid options right in the type signature. Compare that to typing the parameter as plain string, which would silently accept a typo like "lft" and only fail once the program is running.
function swipe(direction: "left" | "right") {
console.log(`Swiped ${direction}`);
}
swipe("left"); // fine
swipe("up");
// Error: Argument of type '"up"' is not assignable to
// parameter of type '"left" | "right"'.type Direction = "left" | "right"; combines two literal types using a ____ type.
Why prefer function swipe(direction: "left" | "right") over function swipe(direction: string)?
let status: "on" | "off" = "on"; can later be reassigned to "standby" without a compiler error.
Special Types
10 questions · pass with 60% — just like in the app.
What does giving a variable the any type do?
Calling a method that does not exist on an any-typed value is caught by the compiler.
Overusing any defeats the purpose of TypeScript because it removes the ____ that the type system is meant to provide.
What must you do before using a method or property on a value typed unknown?
A variable typed unknown can be assigned a string, then later a number, with no error.
if (typeof value === "string") { value.toUpperCase(); } works because the typeof check ____ value from unknown to string.
What values does the type "left" accept?
type Status = "on" | "off"; is an example of combining literal types with a union.
function move(dir: "up" | "down") rejects a call like move("sideways") because "sideways" is not part of the ____.
Compared to typing a parameter as plain string, a literal union like "left" | "right" mainly gives you:
Keep your streak going in Swipe Coding
Swipe through every level of TypeScript on your iPhone — with XP, stars, streaks, a personal advisor and the full track beyond these free levels.
Get the Swipe apps →