Lessons · TypeScript · a type of exact values
Exactly these strings
'GET' | 'POST' is a union of string literal types: the value must be one of those exact strings. A typo is a compile error.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Status names, HTTP methods, event kinds: strings that mean something specific. Literal types make the compiler check the spelling everywhere they are used.
How to think about it
Name the union once as a type, then use it for parameters and fields. When a plain string must be passed, narrow it first or declare it as const.
Worked example
type Method = "GET" | "POST";Only those exact strings.
let m: Method = "GET";Fine.
m = "PUT";Error: 'PUT' is not a Method, a typo caught before it runs.
function send(method: Method, url: string) { return method + " " + url; }Callers cannot misspell the method.send("POST", "/api");Fine.Your turn
Three allowed levels.
type Level = "low" | | "high";
Solve one with the compiler running
The trap
A variable declared as let holds string, not the literal, so it cannot be passed where a Method is expected even when it contains 'GET'. Use as const or the type.