Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 96 ยท Basic Types

Literal Types and as const

Learn TypeScript literal types - exact string, number and boolean types, literal unions, widening with let and const, as const and unions derived from values.

So far, types have described kinds of values: any string, any number. But many values in a program are only allowed to be a few exact things. An HTTP method is 'GET', 'POST', 'PUT' or 'DELETE', not any string. A die shows 1 to 6. A toggle is 'on' or 'off'. TypeScript can express this precisely with literal types: types whose only value is one specific string, number or boolean.

On their own, literal types aren't very exciting. Combined with union types, they become one of TypeScript's best features: a list of allowed values that the compiler enforces, your editor autocompletes, and a typo can't slip past. This lesson also explains widening (why let and const infer different types) and the as const assertion, which keeps values as narrow as possible.

Literal types

Any string, number, bigint or boolean value can be used as a type. The type 'north' has exactly one value, the string 'north':

TypeScript Literal unions as allowed values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints Moving 3 step(s) north, POST /orders and true. In roll(), Math.floor(...) produces a plain number, and TypeScript can't prove the arithmetic stays between 1 and 6, so the code uses as DieFace, a type assertion that says "trust me". Assertions skip checking, so use them only when you know more than the compiler; Type Assertions and the Non-Null Operator covers when they're appropriate.

Passing a value outside the union is an error, and the message names the allowed type:

TypeScript Values outside the union (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(8,6): error TS2345: Argument of type '"North"' is not assignable to parameter of type 'Direction'.
main.ts(9,7): error TS2322: Type '7' is not assignable to type 'DieFace'.
main.ts(10,5): error TS2322: Type 'false' is not assignable to type 'true'.

Literal types are case-sensitive: 'North' isn't 'north'. And yes, true and false are literal types too. In fact, boolean is simply the union true | false, which is why narrowing a boolean with if (flag) works the same way as narrowing any other union.

Widening: const vs let

Hover over these two variables in an editor and you'll see different types:

TypeScript
const fixed = 'north';   // type: 'north'
let changing = 'north';  // type: string

A const can never be reassigned, so TypeScript gives it the narrowest type: the literal 'north'. A let might be reassigned later to any other string, so TypeScript widens its type to string. This is usually exactly what you want. It becomes a problem when a value is stored somewhere mutable and later passed to something that expects a literal union.

The classic case is an object. Object properties are mutable, so their literal values widen too:

TypeScript Widened object properties (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(8,6): error TS2345: Argument of type 'string' is not assignable to parameter of type 'HttpMethod'.
main.ts(11,6): error TS2345: Argument of type 'string' is not assignable to parameter of type 'HttpMethod'.

Even though req is declared with const, only the variable is constant. req.method = 'DELETE' would still be allowed, so TypeScript infers { method: string; url: string }. The same goes for the let.

There are several good fixes. Pick the one that matches your intent:

TypeScript Four ways to keep a literal type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

All four calls succeed and print their method and URL. Annotation (fix 1) is the most explicit and is the right choice when the object has a known shape you reuse. as const (fixes 3 and 4) is handy for one-off values. A fifth option, the satisfies operator, checks an object against a type without widening it; it has its own lesson, The satisfies Operator.

You also don't need any of this when an object literal is written directly where the type is known, for example send2({ method: 'GET', url: '/e' }) for a function that takes { method: HttpMethod; url: string }. The expected type flows into the literal (contextual typing, from Type Inference), so 'GET' stays a literal.

as const in depth

as const is a const assertion. It tells TypeScript: "this value will never change, so infer the narrowest possible type". It has three effects, applied all the way down through nested objects and arrays:

  1. Literal values keep their literal types ('GET', not string).
  2. Every object property becomes readonly.
  3. Array literals become readonly tuples (readonly [1, 2, 3], not number[]).
TypeScript What as const infers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program prints 8080 search 2, then the object. Uncomment either line at the end and the run stops with the error from the comment.

as const only works on literal expressions: string, number, boolean, array and object literals (and template literals). You can't write someVariable as const. Like all type-level features, it disappears at runtime: the object isn't frozen. If you need runtime immutability too, combine it with Object.freeze() as shown in Readonly and Immutability.

Deriving a union from a value

Often you need the allowed values twice: once as a type, to check your code, and once as a runtime list, to validate input, fill a dropdown or loop over them. Writing both by hand means they can drift apart. With as const, you write the list once and derive the type from it:

TypeScript One list for types and runtime checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output grants editor and admin and rejects owner with the list of valid roles. Two new pieces of syntax appear here, both explained in later lessons:

  • typeof ROLES in a type position means "the type of the value ROLES", and [number] reads the element type of an array or tuple. keyof, typeof and Indexed Access Types covers both.
  • value is Role is a type predicate: when isRole returns true, TypeScript narrows the argument to Role. See Custom Type Guards.

The cast ROLES as readonly string[] is needed because includes on a tuple of literals only accepts those literals, and value is any string. Widening the array for the check is safe.

Add a fourth role to the array, and the Role type, the runtime check and the error message all update automatically.

Objects as enum-like constants

The same idea works for objects. A const object gives you readable names at runtime and a union type of its values:

TypeScript An as const object instead of an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints Hello TypeScript, [draft] Literal types, (Old news) and [ 'draft', 'published', 'archived' ]. Using the same name Status for the value and the type is legal (values and types live in separate namespaces) and a common convention.

TypeScript also has a dedicated enum keyword. Many teams prefer literal unions and as const objects because they're plain JavaScript values with no extra runtime code and they work with Node's built-in type stripping. Enums compares the options fairly.

A taste of template literal types

Literal types can also be built from patterns. A template literal type uses backtick syntax at the type level to describe strings with a specific format:

TypeScript
type Size = `${number}px` | `${number}%`;
const width: Size = '120px';     // OK
const height: Size = '50%';      // OK
// const bad: Size = '120';      // error: doesn't match either pattern

type Lang = 'en' | 'es';
type Region = 'US' | 'MX';
type Locale = `${Lang}-${Region}`;   // 'en-US' | 'en-MX' | 'es-US' | 'es-MX'

When the parts are unions, TypeScript combines every option. This is powerful for typed event names and CSS values, and it gets its own lesson later: Template Literal Types.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of x in let x = 'hello';?

    A let can be reassigned, so TypeScript widens the literal to string. A const would keep the literal type 'hello'.
  2. 2. Given function go(d: 'up' | 'down') {} and const opts = { d: 'up' };, does go(opts.d) compile?

    Object properties are mutable, so 'up' widens to string. Fix it with an annotation, as const or satisfies.
  3. 3. What is the type of const t = [1, 'a'] as const;?

    as const turns an array literal into a readonly tuple and keeps every element's literal type.
  4. 4. With const SIZES = ['s', 'm', 'l'] as const;, what is (typeof SIZES)[number]?

    Indexing a tuple type with number gives the union of all its element types.
  5. 5. What is the type boolean the same as?

    boolean is the union of the two literal types true and false.

Summary

  • A literal type is a single exact value used as a type: 'north', 42, true. boolean is true | false.
  • Unions of literals ('GET' | 'POST') are TypeScript's lightweight enums: checked, autocompleted and case-sensitive.
  • const variables keep literal types; let variables and object properties widen ('GET' becomes string). Fix widening with an annotation, contextual typing, as const or satisfies.
  • as const keeps literal types, makes properties readonly and turns arrays into readonly tuples, all the way down. It has no runtime effect.
  • Derive unions from values: (typeof LIST)[number] for a const array and (typeof OBJ)[keyof typeof OBJ] for a const object, so the type and the runtime list never drift apart.
  • Template literal types like `${number}px` describe string patterns; they're covered later in the course.

Next: Type Aliases