- 01Getting Started
- 02Your First Output (console.log)
- 03Variables and Type Annotations (number/string/boolean)
- 04Array Types
- 05Function Types (Parameters and Return Values)
- 06Optional Parameters and Default Parameters
- 07Interfaces (interface)
- 08Optional Properties (?)
- 09Type Aliases (type)
- 10Union Types
- 11Literal Types
- 12enum (Enumerated Types)
- 13Classes and Types
- 14Inheritance (extends) and Implementing an Interface (implements)
- 15Generics (<T>)
- 16Tuple Types
- 17The any and unknown Types
- 18Type Assertions (as)
- 19The readonly Modifier
- 20[Applied] Build a Mini Inventory Management System
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).
๐งช 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).
