Literal Types
Intro to Literal Types
Literal types let you model exact values in TypeScript. Instead of saying
"this is a string," you can say "this is the string
'success'." That makes
it possible to model specific states and build safer APIs.const locales = ['en-US', 'es-ES', 'fr-FR'] as const
type Locale = (typeof locales)[number]
function formatLocale(locale: Locale) {
return locale.toLowerCase()
}
By default, TypeScript widens literal values in arrays and objects. That's
often helpful, but it can erase useful information.
as const preserves the
most specific type, keeping your data precise and immutable.const shortcuts = {
save: 'cmd+s',
open: 'cmd+o',
} as const
type ShortcutName = keyof typeof shortcuts
type ShortcutCombo = (typeof shortcuts)[ShortcutName]
as const also makes objects and arrays readonly, which is perfect for
immutable data and tuples.In this exercise, you'll use
as const to turn configuration data into a
source of truth for types, so your types stay correct as data changes.