Objects, interfaces and type aliases
Real programs pass around objects: users, products, orders, API responses. TypeScript lets you name the shape of an object once and reuse it everywhere.
type aliases
interface
An interface describes an object shape too:
Interface vs type: which should I use?
They're nearly interchangeable for object shapes. The practical differences:
interface |
type |
|
|---|---|---|
| Object shapes | ✓ | ✓ |
| Extending | interface B extends A |
type B = A & { … } |
Unions (A | B), primitives, tuples |
✗ | ✓ |
| Declaration merging (re-opening it to add fields) | ✓ | ✗ |
A common convention is to use interface for object shapes (especially public APIs) and type for everything else: unions, functions and computed types. Consistency within a codebase matters more than the choice.
Extending and combining
Nested objects and arrays of objects
Index signatures and Record
For objects used as dictionaries, with keys you don't know in advance:
Excess property checks
TypeScript is extra strict when you write an object literal directly. It flags properties that don't belong, which catches typos:
Classes implement interfaces
private, public, protected and readonly modifiers on constructor parameters are TypeScript shorthand for declaring properties.
Practice
Model a small blog. Create types for an Author (name, optional website), a Comment (author, text, likes) and a Post (id, title, readonly slug, author, tags array, comments array). Then write topComment(post: Post): Comment | undefined, which returns the comment with the most likes.
1.How do you mark an object property as optional?
2.Which can a type alias express that an interface cannot?