Ad space (banner)
Lesson 11 / 20

Literal Types

This lesson covers literal types, which use a specific value itself as a type. It's for anyone searching "TypeScript literal type."

A string or number itself can be used directly as a type, and combined with a union type, you can create a type that "only allows a fixed set of values." For example, writing "small" | "medium" | "large" means nothing but those three strings can be assigned.

The example defines type Size = "small" | "medium" | "large"; and builds a function returning a different price per size. Passing a value that doesn't exist (like "huge") produces a compile error.

A common early mistake is not seeing the difference from a plain string type. A string type accepts any string at all, while a literal type's big difference is that it rejects anything outside the fixed set of candidates.

In real projects, literal types are used a lot for fields with a fixed set of possible values, like an order size or a status ("in progress," "complete," and so on).

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run TypeScript directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)