Ba’zan object ichidagi barcha qiymatlar majburiy bo‘lmaydi. Ya'ni, ayrim property lar bo‘lishi ham mumkin, bo‘lmasligi ham mumkin. Buni TypeScript da optional (ixtiyoriy) qiymatlar orqali hal qilamiz.
📌 Muammo
Masalan:
type User = { name: string age: number }
Endi object yaratamiz:
const user: User= { name: "Ali" }
❌ Error chiqadi Chunki:
age → majburiy (required)
📌 Yechim — Optional property (?)
Agar property majburiy bo‘lmasin desak, ? qo‘yamiz:
type User= { name: string age?: number }
📌 Endi ishlaydi:
const user: User= { name: "Ali" }
✅ age bo‘lmasa ham muammo yo‘q
📌 Optional nimani anglatadi?
age?: number
Bu degani:
age → number bo‘lishi mumkin yoki → undefined bo‘lishi mumkin
📌 Aslida nima bo‘ladi?
age?: number
≈
age: number | undefined
📌 Muammo (ishlatishda)
console.log(user.age.toFixed(2)) // ❌ error
Chunki:
age → undefined bo‘lishi mumkin
📌 Yechimlar
🔹 1. Optional Chaining
console.log(user.age?.toFixed(2))
🔹 2. If bilan tekshirish
if (user.age !== undefined) { console.log(user.age.toFixed(2)) }
📌 Function parametrlarida ham ishlatiladi
function greet(name: string,age?: number) { console.log(name) if (age) { console.log(age) } }
📌 Chaqarish:
greet("Ali") greet("Ali",25)
📌 Default value bilan ishlatish
function greet(name: string,age: number = 18) { console.log(name,age) }
📌 Bu yerda:
age → har doim qiymatga ega bo‘ladi
🎯 Xulosa
Optional values — bu:
Property yoki parametr majburiy emas
📌 Misol:
type User= { name: string age?: number }
💡 Esda tuting:
- ? → optional qiladi
- aslida → type | undefined
- ishlatishda → tekshirish kerak