Menu

Literal Types, Unions, and as const

Lesson 5: Literal Types, Unions, and as const

What is a literal type?

A literal type is a type that allows one exact value. Combined with | (union), literal types describe a fixed set of allowed values.

Type Allows
string Any text
'UPI' Only the text 'UPI'
`'UPI' 'Card'
`1 2
true Only true

Example

type OrderStatus = 'pending' | 'packed' | 'shipped' | 'delivered' | 'cancelled';

let status: OrderStatus = 'pending';
status = 'shipped';    // OK
status = 'lost';
// Error: Type '"lost"' is not assignable to type 'OrderStatus'.

function setDeliverySlot(slot: 'morning' | 'afternoon' | 'evening') {
  // ...
}
setDeliverySlot('night'); // Error

**as const** turns a value into its narrowest, read-only form:

const config = { currency: 'INR', freeDeliveryAbove: 499 };
// type: { currency: string; freeDeliveryAbove: number }

const configConst = { currency: 'INR', freeDeliveryAbove: 499 } as const;
// type: { readonly currency: 'INR'; readonly freeDeliveryAbove: 499 }

const SLOTS = ['morning', 'afternoon', 'evening'] as const;
type Slot = (typeof SLOTS)[number]; // 'morning' | 'afternoon' | 'evening'

How it works

  • const variables infer literal types: const method = 'UPI' has the type 'UPI'. let widens it to string because it may change.
  • Literal unions give you autocomplete in the editor; typing status = ' lists every allowed value.
  • as const on an array plus (typeof X)[number] creates a union from a list, so the values and the type stay in sync.

Common mistakes

Mistake Effect Fix
Using string for a fixed set of values Typos like 'deliverd' are accepted Use a literal union
Passing an object property where a literal is expected string is not assignable to `'UPI' ...`
Repeating the same list as both an array and a type They drift apart Derive the type from an as const array

Key takeaways

  • Literal unions restrict values to an exact set and give great autocomplete.
  • as const keeps values narrow and read-only.

Try it: Create a PaymentMethod type from an as const array of 'UPI', 'Card', 'NetBanking', and 'COD', then write a function that accepts only those values.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details