Literal Types
Constraining values to exact specific strings or numbers.
Beyond 'string'
Often, typing a variable as string or number is far too broad. If you are building a Button component, you don't want the user to pass *any* string as a size, you only want them to pass specific strings.
A Literal Type allows you to specify the exact value that a variable is allowed to hold.
Autocomplete and safety
Using literal types completely changes the developer experience. If a property is typed as string, the developer has to open the documentation to figure out what strings are allowed.
If the property is typed as 'sm' | 'md' | 'lg', their IDE will automatically suggest those three exact strings as they type, and will throw a compiler error if they try to pass 'xl'.
Defining a Literal Union
You define a literal type just by typing the exact string, number, or boolean value you want. Usually, you combine multiple literals using a union (|):
typescript
type ButtonSize = "sm" | "md" | "lg";
let size: ButtonSize = "md"; // OK
size = "xl"; // Error: Type '"xl"' is not assignable to type 'ButtonSize'.
Try it
Try typing an invalid size string into the input field to see how the compiler instantly rejects it.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A Literal Type specifies an exact, specific value (like
'sm'). - Combining them in unions (
'sm' | 'md') creates powerful constraints. - They give other developers instant autocomplete for valid options.
- Object properties infer as general strings unless locked with
as const.
Done with this concept?
Mark it complete to track your progress. No login needed.