TypeScript
Type vs interface
Mikor használj interface-t és mikor type-ot: unionok, primitív aliasok, extends vs intersection, declaration merging.
Type vs interface
Összehasonlítás
| Tulajdonság | interface | type |
|---|---|---|
| Objektumtípus leírása | ✅ | ✅ |
| Primitív alias | ❌ | ✅ |
| Union típus | ❌ | ✅ |
| Intersection | extends | & |
| Deklaráció összevonás | ✅ | ❌ |
Mikor interface?
- objektumok és osztályok leírása
- bővíthetőség (publikus API)
interface User {
id: number
name: string
}
interface AdminUser extends User {
role: "admin"
permissions: string[]
}Mikor type?
- union/intersection
- primitív alias
- tuple
type ID = string | number
type Status = "active" | "inactive" | "pending"
type Coordinate = [number, number]Declaration merging (interface)
interface Window {
myCustomProperty: string
}