BeCuriouzLearn something new every day
Literal Types: When 'GET' Is Its Own Type
💡 A literal type pins a value to one exact option, and unions of literals let TypeScript catch invalid values and narrow to the precise case inside each branch.
So far you've seen broad types like string and number. But TypeScript can go narrower: a literal type is a type whose only allowed value is one exact literal. The type "GET" accepts the string "GET" and nothing else. On its own that seems useless, but combine literals with the union types you saw earlier and you get something powerful:
type Method = "GET" | "POST" | "PUT";
function request(url: string, method: Method) {
// ...
}
request("/users", "POST"); // ✅ ok
request("/users", "POTS"); // ❌ Argument not assignable to MethodThe compiler now blocks typos before the code ever runs — the set of valid strings is baked into the type.
Literal types shine with narrowing: inside a check, TypeScript uses your control flow to shrink a union to a more specific type. After you compare method against a literal, TypeScript knows exactly which case you're in:
function handle(method: Method) {
if (method === "GET") {
// here method is narrowed to "GET"
return fetchData();
}
// here method is "POST" | "PUT"
}One gotcha: TypeScript infers literal types for const, but widens them for let. const m = "GET" has type "GET", while let m = "GET" has the broader type string — because a let variable could be reassigned later.