tezvyn:

Literal Types: Be More Specific Than `string`

AI-drafted, machine-checkedSource: typescriptlang.orgadvanced

Literal types specify the *exact* value a variable must hold, not just its general type like `string`. They're great for creating fixed option sets with unions, like `type Status = "pending" | "complete"`.

WHY IT EXISTS Sometimes a general type like string is too broad. You don't want a function to accept any string, but only one of a few specific strings. Literal types solve this by allowing you to use a concrete value as a type, enabling stronger compile-time checks and better autocompletion.

THE MENTAL MODEL A literal type is a type that represents one single, exact value. Instead of a variable holding a string, it can hold the type "pending". This tells the compiler the variable can only ever be the string "pending", nothing else. It's a guarantee of a specific value, not just a category of value.

HOW IT WORKS TypeScript infers literal types through a process called "narrowing". When you declare a variable with const, TypeScript knows its value can never change, so it narrows the type from string to the specific literal string (e.g., "Hello World"). In contrast, a let variable can be reassigned, so the compiler keeps the wider, more general type (string). You can then combine several literal types with a union (|) to create a type that accepts a finite set of specific values.

WHEN TO USE IT Use literal types to create enum-like behavior with strings, numbers, or booleans. This is common for function parameters that accept a fixed set of options, like type Alignment = "left" | "right" | "center". They are also essential for creating specific function overloads, where the function's return type depends on a specific literal value passed as an argument, like createElement("img") returning an HTMLImageElement.

WHEN NOT TO USE IT Avoid literal types when a value is truly dynamic and can't be constrained to a predefined set. For example, a variable holding user input from a form field should be a string, not a literal type. Overusing literals for values that aren't actually fixed can make your types brittle and hard to maintain.

ONE CANONICAL EXAMPLE Creating a set of allowed animation styles. By defining a union of string literals, you get type safety and editor autocompletion, preventing typos and invalid values at compile time.

type Easing = "ease-in" | "ease-out" | "ease-in-out";

function animate(dx: number, dy: number, easing: Easing) { // ... animation logic }

animate(0, 0, "ease-in"); // Correct animate(0, 0, "uneasy"); // TypeScript Error: Argument of type '"uneasy"' is not assignable to parameter of type 'Easing'.

Read the original → typescriptlang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.