Type aliases and interfaces
Concept and syntax
Use type Item = { ... } or interface Item { ... } to give a reusable name to an object contract. Both can describe a compatible structural object; values need matching members, not a runtime class instance. A type alias can name non-object types such as a union. Interfaces can merge declarations with the same name in a scope, whereas a type alias cannot be redeclared that way. Choose names that explain the data role.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
interface Item { label: string; count: number; }type Entry = { label: string; count: number };const item: Item = { label: "tea", count: 3 };const entry: Entry = item;console.log(entry.label, entry.count);Expected output (one line per log):
tea 3Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
type Entry = { label: string };const entry: Entry = { label: 3 };Expected compiler diagnostic: TS2322. Naming a shape does not convert its property values. Supply a string label.
Practice and recap
Create equivalent named shapes using type and interface. Assign a value between them and then try a mismatched field type.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Type aliases and interfaces — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Which construct can directly name a union of string literals?
Must a value be created by a class named Item to satisfy interface Item?
Which value matches the label property type?
type Entry = { label: string };const entry: Entry = { label: 3 };