Literal Types in TypeScript
Types like number and string accept almost anything. Literal types let you say exactly which values are allowed, so TypeScript catches typos and wrong values before your code runs.
When you give a variable a type like number or string, you’re telling TypeScript what kind of value it holds. But “any number” and “any string” are huge sets. Most of the time, you only expect a handful of them.
Literal types let you list the exact values you expect. Anything else becomes a compile error.
Numbers that are too broad
Say you have a variable for a binary digit. It should only ever be 0 or 1. With the type number, TypeScript is happy with anything. Try the values below and compare the two types:
let binaryNumber: number = ;let binaryNumber: 0 | 1 = ;
With number, a value like 12 slips through without a word. With 0 | 1, the compiler stops you: Type ‘12’ is not assignable to type ‘0 | 1’. You have narrowed the type down to the exact values that make sense.
const binaryNumber: 0 | 1 = 12;Strings work the same way
Literal types are even more useful with strings. A user’s role should be "Admin", "User" or "Guest", not "Apple". Try a few values, including the lowercase "admin":
let userRole: string = ;let userRole: "Admin" | "User" | "Guest" = ;
Give it a name: type aliases
Writing "Admin" | "User" | "Guest" everywhere gets tiring. Pull it out into a type alias and reuse it. Hover over the names below to see their types:
type type Role = "Admin" | "User" | "Guest"Role = "Admin" | "User" | "Guest";
const const userRole: RoleuserRole: type Role = "Admin" | "User" | "Guest"Role = "Guest";
function function setRole(userRole: Role): voidsetRole(userRole: RoleuserRole: type Role = "Admin" | "User" | "Guest"Role) {
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`User role updated to ${userRole: RoleuserRole}`);
}
function setRole(userRole: Role): voidsetRole("Admin");Now setRole only accepts one of the three roles, and the list of roles lives in one place.
The mistake most people make: objects
Here’s a trap. You store the role in an object, then pass it to setRole. It looks correct, but TypeScript complains. Switch between the two versions and click each line:
- const data = {data: { userRole: string }
- userRole: "Admin",userRole: string
- };
- data.userRole = "Mango"; // allowed!userRole: string
- setRole(data.userRole);data.userRole: string
- const data = {data: { readonly userRole: "Admin" }
- userRole: "Admin",userRole: "Admin"
- } as const;
- data.userRole = "Mango";
- setRole(data.userRole);data.userRole: "Admin"
In a plain object, properties can be changed later. Nothing stops someone from writing data.userRole = "Mango", so TypeScript types the property as the broad string, and a string isn’t a Role.
Adding as const makes the object read-only. Now the property can never change, so TypeScript keeps the exact type "Admin", and setRole accepts it. Try to change it, and that line becomes the error instead.
const const data: {
userRole: string;
}
data = { userRole: stringuserRole: "Admin" };
function setRole(userRole: Role): voidsetRole(data.userRole);
const const fixed: {
readonly userRole: "Admin";
}
fixed = { userRole: "Admin"userRole: "Admin" } as type const = {
readonly userRole: "Admin";
}
const;
const fixed: {
readonly userRole: "Admin";
}
fixed.userRole = "Mango";const vs let
One more thing. Remove the type completely and hover over each variable:
const fixedRole = "Guest";
let changingRole = "Guest";A const can never be reassigned, so TypeScript gives it the exact literal type "Guest". A let can change later, so TypeScript widens it to string. Same value, different types, all because of one keyword.
Your turn
This request function only accepts "GET" or "POST". The options object looks right, but TypeScript won’t accept it. Fix the error without changing the request function, then press Run.
Hint: the object's method property is being typed as string. How do you keep it as the exact value?
type Method = "GET" | "POST";
function request(url: string, method: Method) {
console.log(method + " " + url);
}
const options = { url: "/api/users", method: "GET" };
request(options.url, options.method);Click the code to edit it. TypeScript checks it as you type.
Quick recap
- Primitive types like
numberandstringaccept almost any value. - Literal types list the exact values allowed:
0 | 1, or"Admin" | "User" | "Guest". - They catch wrong values and typos at compile time, and give you autocomplete.
- Use a type alias (
type Role = …) to name and reuse them. - Object properties are widened to
stringbecause they can change.as constkeeps the exact values. constkeeps the literal type.letwidens it.