Literal types
- TypeScript course
- Beginner
- Lesson 61/89
- 4 min
Learn literal types, fixed value types.
What is a literal type?
A literal type is a type that specifies an exact value. Combined with unions, you create precise types that allow only specific values.
let direction: "up" | "down";
direction = "up";
direction = "left"; // errorThis is useful when a variable can take only a few fixed values.
Literal unions
You can combine several literal types with | to create a finite set of values. This is similar to a string enum but offers a simpler alternative.
type Status = "open" | "closed" | "pending";
function setStatus(s: Status) {
// ...
}
setStatus("open");
setStatus("done"); // errorType safety is provided at compile time.
Practice Define a role with a literal union
Define the Role type as "admin" | "user" | "guest". Write a function greet(role: Role): string that returns "Welcome, admin" for admin, "Hello, user" for user, and "Hi, guest" for guest. Print the result of all three calls.
Starter code
// Role türünü tanımla: admin, user, guest
// greet(role: Role): string döndürür
// admin ise karşılama mesajı
// user ise selamlama mesajı
// guest ise kısa mesaj
// üç çağrıyı da yazdırSample solution
type Role = "admin" | "user" | "guest";
function greet(role: Role): string {
if (role === "admin") {
return "Welcome, admin";
} else if (role === "user") {
return "Hello, user";
} else {
return "Hi, guest";
}
}
console.log(greet("admin"));
console.log(greet("user"));
console.log(greet("guest"));Expected output
Welcome, admin Hello, user Hi, guest
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following is an example of a literal type?
let direction: ??? = "left";- string | number
- "left" | "right" Correct answer
- Object
- string
Explanation: A literal type uses an exact value (such as "left" or 42) as the type. "left" | "right" is a union of two string literals.
2 Complete the literal value
let color: "red" | "blue" = ____;
let color: "red" | "blue" = "red";
Explanation: Only "red" or "blue" are allowed. "green", "yellow" and "black" are not in the set, so they cause a compile error.
3 Literal parts
| Term | Meaning |
|---|---|
"up" |
A single string literal |
42 |
A single number literal |
"left" | "right" |
A union of two string literals |
type Status = "open" | "closed" |
A type made of a literal union |