Lesson 9 of 15
Literal Types
Literal Types
A literal type pins a variable to a specific value, not just a general type:
let direction: "north" | "south" | "east" | "west";
direction = "north"; // OK
direction = "up"; // Error: '"up"' is not assignable to type '"north" | "south" | "east" | "west"'
Literal types are string, number, or boolean values used as types.
Why Literal Types?
They let you describe a limited set of valid values — like an enum, but lighter:
type Status = "pending" | "active" | "closed";
type Coin = "heads" | "tails";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
Using Literal Types in Functions
type Direction = "up" | "down" | "left" | "right";
function move(dir: Direction, steps: number): string {
return "Move " + steps + " steps " + dir;
}
console.log(move("up", 3)); // Move 3 steps up
console.log(move("left", 1)); // Move 1 steps left
as const for Literal Types
When you declare a variable with const, TypeScript infers a literal type for primitives:
const x = "hello"; // type is "hello", not string
But objects and arrays are still mutable, so TypeScript widens their types:
const config = { mode: "dark", level: 5 };
// type is { mode: string; level: number } — not literal
Use as const to make the entire value deeply readonly with literal types:
const config = { mode: "dark", level: 5 } as const;
// type is { readonly mode: "dark"; readonly level: 5 }
This is especially useful for arrays that should be treated as tuples:
const pair = [1, 2] as const; // readonly [1, 2]
const dirs = ["up", "down"] as const; // readonly ["up", "down"]
Your Task
- Define
type Suit = "clubs" | "diamonds" | "hearts" | "spades". Writefunction cardSuit(suit: Suit): stringthat returns"The suit is: [suit]". - Create a
const COLORS = ["red", "green", "blue"] as const. Writefunction describeColors(): stringthat returns the length and first element:"3 colors, first is red".
TypeScript loading...
Loading...
Click "Run" to execute your code.