Return type
TypeScript'da funksiya return type'i: sintaksis, har bir return yo'lini tekshirish, void, never, Promise<T> va qachon inference yetarli ekani.
26-dars
Return type
Avvalgi darsda parametrlarni type qildik — ular funksiyaga nima kirishini belgilaydi. Return type esa nima chiqishini belgilaydi. TypeScript buni ko'pincha o'zi aniqlay oladi, lekin inference bilan muammo bor: funksiya ichidagi xato funksiyada emas, uni ishlatgan joyda chiqadi.
❌ Inference'ga to'liq ishonilganda:
// user.ts
export function getUser(id: number) {
return { id, nmae: "Ali" }; // imlo xatosi — TS indamaydi, bu "to'g'ri" obyekt
}
// profile.ts — boshqa fayl, boshqa dasturchi
const user = getUser(1);
user.name; // ❌ Property 'name' does not exist on type '{ id: number; nmae: string; }'. Did you mean 'nmae'?
Xato profile.tsda ko'rinadi, holbuki aybdor — user.ts. Funksiya 10 joyda ishlatilsa, 10 ta xato chiqadi.
✅ Return type bilan:
type User = { id: number; name: string };
export function getUser(id: number): User {
return { id, nmae: "Ali" };
// ❌ Object literal may only specify known properties, but 'nmae' does not exist in type 'User'.
// Did you mean to write 'name'?
}
Xato aynan kerakli joyda, bitta marta chiqadi. Return type — funksiyaning va'dasi, TypeScript esa har bir return shu va'daga mosligini tekshiradi.
Qanday ishlaydi?
1. Sintaksis
Return type parametrlar qavsidan keyin yoziladi:
function add(a: number, b: number): number {
return a + b;
}
// Arrow function'da ham xuddi shunday
const multiply = (a: number, b: number): number => a * b;
// Obyekt metodida
const calc = {
divide(a: number, b: number): number {
return a / b;
},
};
2. Har bir return yo'li tekshiriladi
Funksiyada bir nechta return bo'lsa, har biri annotation'ga mos kelishi kerak:
function parseAge(input: string): number {
if (input === "") {
return null; // ❌ Type 'null' is not assignable to type 'number'. (5-dars)
}
return Number(input);
}
// Agar null ham ehtimoliy natija bo'lsa — buni ochiq aytish kerak
function parseAge2(input: string): number | null {
if (input === "") return null; // ✅
return Number(input);
}
Endi chaqiruvchi nullni tekshirishga majbur.
3. void — hech narsa qaytarmaydigan funksiya
Natija ishlatilmasligi kerak bo'lgan funksiyalar uchun:
function log(message: string): void {
console.log(message);
}
function save(): void {
return 42; // ❌ Type 'number' is not assignable to type 'void'.
}
4. never — hech qachon qaytmaydigan funksiya
Har doim xato tashlaydigan yoki cheksiz ishlaydigan funksiyalar uchun:
function fail(message: string): never {
throw new Error(message);
}
function format(value: string | number) {
if (typeof value === "string") return value;
if (typeof value === "number") return value.toFixed(2);
fail("Kutilmagan qiymat"); // TS biladi: bu yerdan keyin kod davom etmaydi
}
5. async funksiyalar — Promise<T>
async funksiya har doim Promise qaytaradi, shuning uchun return type ham Promise bo'lishi shart:
async function fetchUser(id: number): User {
// ❌ The return type of an async function or method must be the global Promise<T> type.
// Did you mean to write 'Promise<User>'?
}
async function fetchUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return res.json(); // ✅
}
6. Maxsus return type'lar
Keyinroq ko'radigan ikkita maxsus shakl — ular oddiy boolean/void emas, balki TypeScript'ga narrowing uchun ma'lumot beradi:
function isString(x: unknown): x is string {
return typeof x === "string";
}
function assertDefined<T>(x: T): asserts x is NonNullable<T> {
if (x == null) throw new Error("Qiymat yo'q");
}
7. Qachon yozish kerak, qachon inference yetarli?
| Holat | Tavsiya |
|---|---|
export qilingan, boshqa fayllar ishlatadigan funksiya |
✅ Return type yozing |
| Kutubxona / public API | ✅ Albatta yozing |
| Rekursiv funksiya | ✅ Yozing (aks holda TS ba'zan type'ni aniqlay olmay xato beradi) |
| Bir nechta murakkab return yo'li | ✅ Yozing |
| Kichik, lokal yordamchi funksiya | Inference yetarli |
Callback (map, filter ichida) |
Inference yetarli |
Return type'ni funksiyadan "sug'urib olish" ham mumkin — ReturnType<typeof fn>. Bu utility type'ni keyingi darslarda batafsil ko'ramiz.
Eng ko'p uchraydigan xato
Bir tarmoqda returnni unutish. Inference'ga ishonilganda, return unutilgan tarmoq jimgina undefined qo'shib yuboradi:
function getDiscount(level: "bronze" | "silver" | "gold") {
if (level === "bronze") return 5;
if (level === "silver") return 10;
if (level === "gold") {
console.log("Gold mijoz");
// return 20; ← unutildi
}
}
// TS xulosasi: getDiscount(): number | undefined — hech qanday ogohlantirishsiz
const price = 100 - getDiscount("gold");
// ❌ 'getDiscount(...)' is possibly 'undefined'. — xato yana ishlatilgan joyda
Eng yomoni — agar natija biror joyga any orqali o'tsa yoki strict o'chiq bo'lsa, 100 - undefined = NaN bo'lib, xato umuman ko'rinmaydi.
✅ Return type yozilganda TypeScript muammoni darhol funksiyaning o'zida ko'rsatadi:
function getDiscount(level: "bronze" | "silver" | "gold"): number {
// ❌ Function lacks ending return statement and return type does not include 'undefined'.
if (level === "bronze") return 5;
if (level === "silver") return 10;
if (level === "gold") {
console.log("Gold mijoz");
}
}
Tuzatilgan va kelajakka chidamli versiya — switch bilan:
function getDiscount(level: "bronze" | "silver" | "gold"): number {
switch (level) {
case "bronze": return 5;
case "silver": return 10;
case "gold": return 20;
}
} // ✅ TS barcha holatlar qamrab olinganini biladi
Endi levelga "platinum" qo'shilsa, TypeScript yana shu funksiyada xato beradi — siz uni unutib qo'ya olmaysiz.
Qo'shimcha himoya uchun tsconfigda noImplicitReturns: true yoqish mumkin — u return type yozilmagan funksiyalarda ham "Not all code paths return a value." xatosini beradi.
Esda tuting: inference "funksiya nima qaytarayotganini" aytadi, return type esa "nima qaytarishi kerakligini". Xatoni faqat ikkinchisi tuta oladi.