Modeling Data with Unions, Literals and Interfaces
Work through modelling a course catalogue: restrict values with literal unions, describe records with interfaces, and keep narrow types with as const and satisfies.
Contentsand lesson path
On this page
- The task
- Step 1: a closed set with a literal union
- Step 2: the record shape with an interface
- Step 3: build on the model
- Step 4: configuration with as const and satisfies
- Type alias or interface?
- Check your understanding
- Apply it
- Review prompt
Lessons of TypeScript Foundations
- Why Types: Annotations, Inference and the Compiler Concept · 20 min
- Modeling Data with Unions, Literals and Interfaces Worked example · 25 min
- Narrowing and Validating Data You Do Not Control Worked example · 25 min
- Generics and Types Built from Other Types Concept · 25 min
- Lab: Convert a JavaScript Module to Strict TypeScript Lab · 30 min
- Check: Type Puzzles and Compiler Errors Knowledge check · 8 questions
What you will learn
- Annotate functions, objects and arrays where inference is not enough, and model domain data with type aliases, interfaces, literal types and unions.
Prerequisites: JavaScript Foundations
01. The task
You are adding a catalogue section to a learning site. The course data lives in your own code — constants in a data.ts module — plus a small theme configuration. Nothing here comes over the network, so every value is knowable at compile time, and the types can say exactly what is allowed.
In plain JavaScript this data is a matter of convention: nothing stops level: "Beginner" with a capital B, a missing minutes, or a theme mode that the switch statement never heard of. The failures would appear later, in rendered output or in a branch that silently never runs. The task: give the compiler enough description that all three mistakes become compile errors. The tools are the three building blocks in the title — literal types, unions and interfaces.
02. Step 1: a closed set with a literal union
A level is not any string: it is exactly one of three named values. A union type says "one of these", and each member written with quotes is a literal type — the type of that one value. The pipe reads as "or". The type alias gives the set a name you can reuse:
type Level = 'beginner' | 'intermediate' | 'advanced';
const draft: Level = 'Beginner';level.ts(3,7): error TS2820: Type '"Beginner"' is not assignable to
type 'Level'. Did you mean '"beginner"'?The compiler narrowed the complaint down to a casing difference and suggested the fix. This is the everyday pay-off of literal unions: a typo is a compile error instead of a value that flows through the program until some comparison quietly fails. The same pattern covers any closed set — a sort order, a tab name, an HTTP method. A switch or if that compares against the literals is checked too: misspell a case label and the compiler reports it.
03. Step 2: the record shape with an interface
A course record has a fixed shape with per-field rules. An interface names that shape. Two field-level features carry most of the weight: readonly marks fields that must not be reassigned after creation, and ? marks a field that may be absent. Every other field is required — leaving one out is an error, which is exactly what you want for data the UI depends on:
type Level = 'beginner' | 'intermediate' | 'advanced';
interface Course {
readonly id: string;
title: string;
level: Level;
minutes: number;
summary?: string;
}
const draft: Course = {
id: 'css-01',
title: 'CSS layout',
};course.ts(11,7): error TS2739: Type '{ id: string; title: string; }' is
missing the following properties from type 'Course': level, minutesNote what the model does not say. summary?: string means the field may be missing or undefined — code that reads it must handle both, and the compiler enforces that. readonly id does not deep-freeze the object; it only stops draft.id = ... reassignments. And level: Level composes the two previous steps: the record references the union by name, so the closed set is enforced everywhere the field appears.
04. Step 3: build on the model
With the shape in place, the rest of the code can rely on it. A function that takes a Course can read course.summary only after checking it, and an array of courses is simply Course[]. Here is the catalogue rendering, which compiles and runs:
type Level = 'beginner' | 'intermediate' | 'advanced';
interface Course {
readonly id: string;
title: string;
level: Level;
minutes: number;
summary?: string;
}
const gitBasics: Course = {
id: 'git-01',
title: 'Git basics',
level: 'beginner',
minutes: 45,
};
const typeScriptIntro: Course = {
id: 'ts-01',
title: 'TypeScript: first steps',
level: 'beginner',
minutes: 90,
summary: 'Types without the jargon.',
};
function label(course: Course): string {
const tag = course.summary ? ` — ${course.summary}` : '';
return `[${course.level}] ${course.title}${tag}`;
}
const courses: Course[] = [gitBasics, typeScriptIntro];
for (const course of courses) console.log(label(course));[beginner] Git basics
[beginner] TypeScript: first steps — Types without the jargon.The ternary in label is not style: with summary?: string, the type of course.summary is string | undefined. While template literals silently coerce undefined to string, any operation that expects a real string — such as a method call like course.summary.trim() or passing it to a function requiring a string argument — causes the compiler to object unless you narrow it first. The type turns a possible undefined defect into a compile-time conversation.
05. Step 4: configuration with as const and satisfies
The theme configuration has a subtlety. A plain annotation checks the value but then widens what the compiler remembers: annotated as { mode: 'light' | 'dark' }, the field mode is from then on just that union, even though this particular config is always dark. When you want the check and the precise type — usually because other code branches on the exact value — use satisfies: it checks the object against the type while keeping what was inferred:
type ThemeConfig = {
mode: 'light' | 'dark';
accent: string;
};
const config = {
mode: 'dark',
accent: 'teal',
} satisfies ThemeConfig;
console.log(config.mode === 'dark');trueTwo mistakes this construction catches. An invalid value still fails, as any annotation would:
type ThemeConfig = {
mode: 'light' | 'dark';
accent: string;
};
const config = {
mode: 'midnight',
accent: 'teal',
} satisfies ThemeConfig;theme-mistake.ts(7,3): error TS2322: Type '"midnight"' is not
assignable to type '"dark" | "light"'.And because satisfies keeps the inferred type, config.mode here is the literal 'dark' — assigning config.mode = 'light' afterwards is an error, which an ordinary annotation would have allowed. Pair satisfies with as const when a value should stay fully literal and deeply readonly, for example a table of route paths or weights that other types are derived from.
06. Type alias or interface?
For object shapes, interface Course { ... } and type Course = { ... } are close to interchangeable: both describe the same structural type, both support optional and readonly fields, and code written against one accepts values written for the other. The practical difference is range. A type alias can name anything — a union (type Level = ...), a primitive, an array, a function signature — while an interface can only describe object shapes, in exchange for a little extra: interfaces can be extends-ed and can merge with later declarations of the same name.
A simple convention keeps a codebase consistent: use interface for object shapes that other modules implement, and type for everything else — unions, aliases of utility types, derived types. Do not invent a third convention per file; the compiler does not care, and your colleagues do.
07. Check your understanding
08. Apply it
Take a constants file from one of your own projects — navigation items, feature flags, category lists — and model it: a literal union for every closed set, an interface for every record shape, as const on tables other code derives from. Then delete a field that a rendering function uses and watch where the compiler points. If your data arrives from an API rather than your own code, hold that thought: the next lesson handles data the compiler cannot see. The catalogue built here is also the shape of the practice task for this skill, converting a search module to strict TypeScript.
09. Review prompt
Without looking back: write a union type for a traffic light from memory, and say what the compiler reports for a misspelled member. What do ? and readonly each change about a field? And explain in one sentence why satisfies exists when annotations already check values.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.