TypeScript Fundamentals
Structural Typing
TypeScript is mostly structurally typed: compatibility is based on shape rather than declared name. If a value has the required properties, it can usually be used as that type.
- Shape matters more than names
- This matches JavaScript's object model
- Structural typing makes APIs flexible
- It can blur domain boundaries
- Classes are not automatically nominal
type User = { id: string }
type Product = { id: string }
const product: Product = { id: "p1" }
const user: User = product // allowed: same structure| Model | Compatibility based on | Example |
|---|---|---|
| Nominal | Declared identity/name | Java class hierarchy |
| Structural | Required shape | TypeScript object types |
| Branded structural | Shape + phantom marker | UserId vs ProductId |
| Runtime validation | Actual value check | Parser/schema |