Oldingi darslarda biz primitive typelar bilan ishladik:
string number boolean
va shuningdek:
arrays tuples
Lekin JavaScript va TypeScript da juda ko‘p ishlatiladigan yana bir muhim narsa bor — bu objects.
📌 Object nima?
Object — bu bir nechta qiymatlarni bitta strukturada saqlaydigan ma'lumot turi. Masalan:
const user = { name:"Ali", age:25 }
Bu object ichida:
name → string age → number
📌 TypeScript object typeni qanday tushunadi?
TypeScript bu objectni avtomatik aniqlaydi:
name → string age → number
Bu type inference orqali bo‘ladi.
📌 Object type ni explicit yozish
TypeScript da object typeni o‘zimiz ham yozishimiz mumkin. Masalan:
let user: { name: string age: number }
Misol
let user: { name: string age: number } user = { name: "Ali", age: 25 }
❌ Noto‘g‘ri misol
user = { name: "Ali", age: "25" }
Error bo‘ladi. Chunki:
age → number bo‘lishi kerak
📌 Object ichida array bo‘lishi ham mumkin
Masalan:
let person= { name: "Ali", age: 25, hobbies: ["sports","cooking"] }
Bu yerda:
hobbies → string[]
📌 Object ichida function ham bo‘lishi mumkin
Masalan:
let person = { name: "Ali", age: 25, greet() { console.log("Hello") } }
⚠️ Muhim eslatma
TypeScript da:
object
type ham bor. Lekin bu juda umumiy type. Masalan:
let user: object
Bu yaxshi emas, chunki TypeScript object ichidagi propertylarni bilmaydi. Shuning uchun odatda object structure yoziladi.
🎯 Xulosa
Object type yozish:
let user: { name: string age: number }
Bu TypeScript ga aytadi:
object ichida name → string age → number
💡 Keyingi dars “Enums” haqida bo‘ladi. Bu TypeScript dagi eng foydali featurelardan biri.