TS Literal Types

TypeScript Literal Types

A literal type represents an exact, specific value rather than a broad category.

Instead of saying a variable is a generic string, you say it is specifically "Hello".

Combining literal types with unions creates highly restricted and intensely safe configurations.

It ensures a variable can only ever accept a predefined set of specific values.


1. String and Number Literals

You can create literal types for strings, numbers, and even booleans.

If you try to assign any other value, the compiler throws an immediate error.

This is incredibly useful for configuration objects, API endpoints, and button states.

It essentially behaves like a lightweight, inline alternative to Enums.

Literal Types Example:

// The variable can ONLY be one of these three exact strings
type ButtonSize = "small" | "medium" | "large";

let btn: ButtonSize = "medium"; // Valid // btn = "huge"; // Error: Type '"huge"' is not assignable.

// Number literal type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;

console.log("Selected Size:", btn);


2. Const Assertions (as const)

When you define an object or array, TypeScript infers its properties as mutable broad types.

By adding as const to the end, you permanently freeze the entire structure into strict literals.

It automatically applies the readonly modifier deeply to every single nested property.

This guarantees your application settings and constants are never accidentally mutated.

Const Assertion Example:

const HTTP_METHODS = ["GET", "POST", "PUT"] as const;

// HTTP_METHODS.push("DELETE"); // Error! Array is completely readonly.

const config = { url: "https://api.example.com", version: 2 } as const; // config.url is literally "https://api.example.com", not just a generic string.

console.log(config.url);


3. SEO and Configuration Safety

Strict literal settings ensure your routing, fetching, and configurations are bulletproof.

Broken links or invalid API states cause massive penalties to site usability and SEO scoring.

Const assertions provide an iron-clad layer of security for production deployment configurations.

Safe Routing Example:

type Routes = "/home" | "/about" | "/contact";

function navigate(route: Routes) { console.log("Navigating to: " + route); }

navigate("/home");


Exercise

?

Which syntax converts an entire object into a deeply nested, readonly literal type?


4. Final Thoughts

Literal types provide unbelievable precision for modeling specific web development states.

The as const assertion is a favorite trick among advanced TypeScript engineers.

Next, we'll look at organizing massive codebases using Namespaces!