Literal types allow you to specify exact constant values ("success", 404, true) as types instead of broad primitive types (string, number, boolean).
"GET" | "POST" | "PUT" | "DELETE".200 | 201 | 400 | 404 | 500.true or false.// Union of String Literal Types
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
// Union of Numeric Literal Types
type AllowedPorts = 80 | 443 | 8080 | 3000;
interface ApiRequest {
url: string;
method: HttpMethod;
port: AllowedPorts;
}
function sendRequest(req: ApiRequest): void {
console.log(`Sending ${req.method} request to ${req.url}:${req.port}`);
}
sendRequest({
url: "https://api.kodersolution.com/v1/data",
method: "POST",
port: 443
});
// sendRequest({ url: "...", method: "PATCH", port: 443 }); // Compiler Error: Type '"PATCH"' is not assignable to type 'HttpMethod'
as const When Passing Literal Objects: Prevents automatic type widening when passing literal object parameters.Define a literal union type Theme that accepts "light" | "dark" | "system". Assign a valid theme value to a variable.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With