All posts

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:

Will TypeScript accept it?
Try a value
  • 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.

The real compiler agrees
const binaryNumber: 0 | 1 = 12;
Type '12' is not assignable to type '0 | 1'.

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":

Which roles get through?
Try a value
  • 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:

A reusable Role type
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[]): void
The **`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:

Why the object fails, and the fix
  1. const data = {data: { userRole: string }
  2. userRole: "Admin",userRole: string
  3. };
  4. data.userRole = "Mango"; // allowed!userRole: string
  5. setRole(data.userRole);data.userRole: string
Tip: click any line to see what TypeScript knows there.

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.

Both errors, from the real compiler
const 
const data: {
    userRole: string;
}
data
= { userRole: stringuserRole: "Admin" };
function setRole(userRole: Role): voidsetRole(data.userRole);
Argument of type 'string' is not assignable to parameter of type 'Role'.
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";
Cannot assign to 'userRole' because it is a read-only property.

const vs let

One more thing. Remove the type completely and hover over each variable:

Same value, different types
const fixedRole = "Guest";
const fixedRole: "Guest"
let changingRole = "Guest";
let changingRole: string

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.

🧩 Your turn

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.

🎉 Nice! No type errors. TypeScript is happy now.

Quick recap

  • Primitive types like number and string accept 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 string because they can change. as const keeps the exact values.
  • const keeps the literal type. let widens it.