Literal types
A literal type is a type that accepts one exact value, like "GET" or 42, instead of any string or number.
Normally string accepts any text. A literal type is stricter: "GET" accepts only that exact text. They also exist for numbers (3) and booleans (true).
A single literal is rarely useful. Its strength shows when you combine them with | in a union: "GET" | "POST" | "DELETE" is a closed list of allowed values.
In the course you see it in request(method: "GET" | "POST" | "DELETE", url: string). If you pass "PUT", the type checker rejects it before anything runs. A typo never reaches production.
The type checker uses these types only while checking. When Node runs the code, the types are gone: method is a plain string.
Reach for it when: a value can only be one of a small, known set, like an HTTP method, a status or an option.
Examples
Common mistake
function request(method: "GET" | "POST", url: string) {
return method + url;
}
console.log(request("PUT", "/users"));Why: "PUT" is not in the list of allowed values, so the type checker rejects it.
How to write it: Use an allowed value, or add "PUT" to the union if it should be valid.
Common mistake
let method = "GET";
function send(m: "GET" | "POST") {
return m;
}
console.log(send(method));Why: With `let`, TypeScript infers `string`, because the variable could change. A `string` does not fit a literal.
How to write it: Declare with const method = "GET", or annotate let method: "GET" | "POST" = "GET".
